FBF Background Image Resizing that keeps aspect ratio
UPDATE: This post now covers both AS2 and AS3 implemention!
Problem: This recently came up in a job, so I thought I would post about it. Basically, I needed to have a background image in a full browser flash site. However, just setting
(in AS2)
image._width = Stage.width;
image._height = Stage.height;
(in AS3)
image.width = stage.stageWidth;
image.height = stage.stageHeight;
wasn’t going to cut it - the image would get all distorted unless the user happened to have their browser set at the correct aspect ratio. I needed the image to resize proportionately.
Solution: To fix the problem, I wrote a simple little conditional statement that dynamically checks the aspect ratio of the image, and that of the stage, and keeps the image filling the stage and in proportion (in other words, if the the image is wider than it is tall, and the stage is taller than it is wide, or the aspect ratio of the stage is higher than the image, the image will fill either the width or height of the stage, and crop the edges).
That doesn’t make a lot of sense, so here’s an example of the finished product. Try resizing the browser to see the effect. Enjoy the mighty Jaguarundi:
Frye / Wiles Proportional Image Scaling in Full Browser Flash (give it a sec to load, it doesn’t have a preloader)
Here’s how I did it:
AS2 Implementation
NOTE: These are the instructions for Actionscript 2. The technique is almost exactly the same in AS3, just the syntax is a little different. See the AS3 code and explanation below.
Create a new flash document. Import an image, and make it into a movie clip symbol. In the symbol, align the picture center on the stage (use the align tools). Give the symbol an instance name of ‘pic’. Now go to the actions panel.
Next set the stage to work for Full Browser. Please note, the way this calculation is working, the stage alignment needs to be set up for Top Left (TL):
Stage.align = "TL";
Stage.scaleMode = "noScale";
Define dynamic aspect ratios
picHeight = new Object ();
picHeight = pic._height / pic._width;
picWidth = new Object ();
picWidth = pic._width / pic._height;
Make a conditional statement to account for various initial browser sizes and proportions
if ((Stage.height / Stage.width) < picHeight) {
pic._width = Stage.width;
pic._height = picHeight * pic._width;
} else {
pic._height = Stage.height;
pic._width = picWidth * pic._height;
};
Center picture on stage
pic._x = Stage.width / 2;
pic._y = Stage.height / 2;
Create a listener to…er…listen for browser size changes
sizeListener = new Object();
Make the listener change picture size and center picture on browser resize
sizeListener.onResize = function() {
if ((Stage.height / Stage.width) < picHeight) {
pic._width = Stage.width;
pic._height = picHeight * pic._width;
} else {
pic._height = Stage.height;
pic._width = picWidth * pic._height;
};
pic._x = Stage.width / 2;
pic._y = Stage.height / 2;
}
Add listener to stage
Stage.addListener(sizeListener);
That should be it! Test our your movie, and it should scale like magic.
AS3 Implementation
If you want to build this in Actionscript 3, you need to keep a couple of things in mind:
- you no longer use the preceding underscore in x, y, height, width, etc values
- the addListener method no longer works, you now must use an addEventListener on the stage. This syntax is quite a bit different.
- Stage.width and Stage.height are now written stage.stageWidth and stage.stageHeight
- Stage.align and Stage.scaleMode are now stage.align and stage.scaleMode
A lot of the syntax changes in AS3 were made to make the language more consistent. It’s a little annoying migrating code, but it’s for the better in the long run.
So, in AS3, your code would look like this:
//set stage for FBF
//set stage for FBF
stage.align = "TL";
stage.scaleMode = "noScale";
//define dynamic aspect ratios
var picHeight = pic.height / pic.width;
var picWidth = pic.width / pic.height;
//add event listener to the stage
stage.addEventListener(Event.RESIZE, sizeListener);
//conditional statement to account for various initial browswer sizes and proportions
function scaleProportional():void {
if ((stage.stageHeight / stage.stageWidth) < picHeight) {
pic.width = stage.stageWidth;
pic.height = picHeight * pic.width;
} else {
pic.height = stage.stageHeight;
pic.width = picWidth * pic.height;
};
}
//center picture on stage
function centerPic():void {
pic.x = stage.stageWidth / 2;
pic.y = stage.stageHeight / 2;
}
// make listener change picture size and center picture on browser resize
function sizeListener(e:Event):void {
scaleProportional();
centerPic();
}
//run initial locations and size
scaleProportional();
centerPic();
If you want source files, here you go (NOW IN AS2 and AS3!):
PLEASE NOTE: If you are in Internet Explorer, you may need to right-click on this link and choose “Save Target As…”
PLEASE NOTE #2: This tutorial is provided as-is, and is intended to intermediate flash users. Unfortunately, we don’t have the time or resources to troubleshoot everyone’s projects, and we cannot help you learn Flash.

264 comments so far.
i need to perform this action on a non flash site, is there any way to do this using javascript?
I’ve seen it done, presumably using Javascript, but I’ve never attempted it myself. A Google search for “javascript background image scaling” might help you out a bit. On the plus side, CSS3 will support background image sizing, so soon it will be possible without any scripting!
hi Rob, thanks for this tutorial, i’ve been looking for something like this. However, i have a question, what if the picture is in portrait/vertical format and i want only the pic height that follows the browser height, but not the width (there will be space in the left and right of the picture)? I hope you get what i mean, sorry my English is not so good.
Thanks in advance
You should be able to do that by removing the conditional statements (the if…else thing) in the setup and the listener, and only leaving the calculation for height, like this:
pic._height = Stage.height;
pic._width = picWidth * pic._height;
hi, i tried your example with other image, but if i export movie the swf dont stretch or crop the image. I just put the new image in the symbol named pic and then drag into scene. Is there any other setting that i forget? in export for example… Thanks
How would I add this in part of a website? For example If I just wanted it to be at the side of something like below the navigation of a website?
Miffo: It sounds like you forgot to give the movie clip an instance name. This is different from the name you give it in the library. Click on the movieclip once it’s in the stage, and then go to your Properties panel. You should see a place to name the instance. Name it pic. If in doubt, download my source files and take a look at how I did it. The link is at the bottom of the article.
Michael: Your question is a bit out of the scope of this tutorial. Try asking around on a flash message board, like http://www.flashkit.com or http://www.actionscript.org
thanks, it works now.
Hi Rob,
thanks for this tutorial. I have been looking at how to do this and this has been I great piece..
I don’t know if this is out of the scope of this tutorial but I am working on a website where I need to do this rescaling in a gallery but keep all of the navigation in the proper place. Like the following site:
http://www.paprika.com/ in their portfolio section is what I am referring to.
How would go from this rescaling to integrating this into a website like this. And note if this too much too ask we could discuss a more formal arrangement for info.
Let me know…..thanks!
Eric,
What you are asking is actually quite easy - Actionscript will only scale what you tell it to scale. If you place another element on the stage, but don’t tell it to scale, it will remain the size that it is. Look up in the tutorial on this page - see where it says Center picture on stage? And then that is repeated within the listener as well? That is actionscript dynamically positioning the element (in this case, it makes it right in the middle of the stage, but you can also assign it pixel x and y coordinates, or make it relative to another instance). You would add in another couple of lines like that (inside and outside of the listener) to determine the positioning of your navigation, but don’t assign any ._height or ._width to your navigation.
-Rob
Hi Rob,
thanks for the response. I think I get what you mean and will experiment. Did you see how the pics in the paprika sight start at a certain size and then scale up? I was trying to get this to do that but did not have any luck.
I am curious…I know a Rob in the Minneapolis/St.Paul area who is a flash developer - are you him?
Hi Again,
just looked through your site and realized that you are not him.
I was wondering if you are open to some sort of consultant role in this project that i am doing ( paid of course). Most of it would be in making sure that the basic structure of the site was set up based on the rescaling aspect of the gallery in conjunction to the navigation.
Would you be open to this?
Let me know when you have a minute…Thanks!
We can definitely do consultation. I emailed you about it.
hi rob.
I really like what you’ve done, Ive seen many like this but the quality is poor.
However im a novice and need more detailed instructions on how to insert the code, do you think you could provide me with this? it would be much appreciated if you could
many thanks
Hi Ron,
I admit, the tutorial is aimed at those who know the basics of flash already. I would suggest going through some of the flash tutorials first, and getting a basic knowledge of the terminology and the usage of actionscript. There are many good books for this as well.
We can also offer consulting services, if you are working on a project that has a budget.
Thanks for the tutorial. As an exercise I’m trying to duplicate what you’ve done and am getting some funky output.
Could I have you look at my file and triage it. I’m sure you could glance at it and find the issue in a matter of seconds. If you could allow me to email you my .fla file I could use some assistance because I’m stuck.
Please help a newbie.
Hey BJ, try downloading my source files. Chances are pretty good that if you duplicated the actionscript, your problem is in your instance names (if they exist). Don’t forget that actionscript is case-sensitive.
I looked back over everything and downloaded the source files and have the same issue. The pic is dynamically resizing but not filling the space in all instances and sometimes panning instead of resizing in some instances.
I went so far as to swap out my image with your image in context of your code and I get the same problem . would my image size and format have anything to do with this issue (1024×768 .png image)?
Image size and format should not matter.
Hi Rob
Ive had a good look through and read alot but still none the wiser.
At the moment i’m just copying and pasting all your code into the actions window with current selection select.
Many Thanks
Hi Rob
I have it scaling in flash when i preview it!
But when i publish it and open the html file it doesnt!
Any ideas?
Many Thanks
It probably has to do with your HTML publish settings. Go to the HTML tab in the Publish Settings window (under File), and for Dimensions, select Percent and put it on 100 x 100.
When I test the code the image is displayed at a quarter of the original size. And positions itself to the lower left. It’s almost doing the exact opposite of what it should be doing.
The source file has no extension I tried:
.fla
.exe
.swf
nothing seems to work? Any suggetions? Thanks.
The source code file is a zip
Many Thanks Rob
Got it going and i love it!!!
Can it be used in a simple prev/next slideshow?
Im just trying it with 2 images and this:
stop () ;
next_btn.onRelease = function () {
if (_root._currentframe == 2) {
gotoAndStop (1);
}
else {
nextFrame() ;
}
}
prev_btn.onRelease = function () {
if (_root._currentframe == 1) {
gotoAndStop (2);
}
else {
prevFrame() ;
}
}
It works fine but the scaling is very pixelated now!
Any ideas?
Many Thanks again!
Hey Ron,
There is no reason my full browser framework wouldn’t work for a slideshow, but I don’t think using the timeline for this is the right approach. I would highly recommend using a non-timeline-based solution. Look into using an array and some looping for this, it will work better. Unfortunately, this is beyond the scope of this tutorial, but I may do a followup at some point in the future that addresses your idea.
Rob
Many Thanks for your reply.
Could you tell me what to look for
so i can go a research or is it simply
array and looping i need to look into.
Thankkyou
That should be a good start, at least. Try some actionscript forums, like actionscript.org if you need more help with it.
Hello,
This looks like a great sample. I need to do the same thing, however I am having trouble downloading the source code. Will you be able to email me that.
Also, are you using a JPG image here OR is it some vector format.
Thanks and appreciate your help.
Hey Rick,
If you’re in Internet Explorer 7, you may need to right-click on the link and choose “Save Target As…” You will then need something that can open a .zip file.
This script will proportionately scale anything in flash, including jpgs, other bitmapped image files and vector data. The example uses a JPG.
Hi rob
ive used this a few times and its worked great!!!
However im trying to apply it to and externally loaded image.
Is this possible?
All im using is:
this.createEmptyMovieClip (”container_mc”,this.getNextHighestDepth());
container_mc.loadMovie(”images/0.jpg”);
It should work with an externally loaded image, although I haven’t tried it. Maybe I’ll make a tutorial for that next.
I’m not sure where/how to insert it
Hi Rob,
Hope you can help,
I have tested you tutorial and it works perfectly.
However, I am trying to fade my image in from 0% Alpha 100% using a motion tween. To give a nice transition whilst keeping the image in proportion? Can you help?
hi Rob
I was curious for this tutorial, however the zip you provided seems to be damaged (cannot be extracted here). Would it be able to provide/send another copy?
Thanks alot,
Frank
Jason:
Put the motion tween in the ‘pic’ instance.
Frank:
If you are using internet explorer, you may need to right click on the file and hit ‘Save Target As…’ I just downloaded the file and it worked fine. Also, it’s in Flash 8 format, so if your flash is older than that you might have problems.
thanks alot Rob, I downloaded the zip via FF and it works fine now. I’s a nice, multibrowser script.
The only problem I have left is centering (horizontal, vertical) the content above it (as publish setting are ‘top and ‘left’).
Do you have any suggestion or useful link regarding combining fullbrowser bg-image and centered content? (seems hard to find)
Thanks!
Hey frank,
You can center within the TL setup by dividing the stage. You would use something along the lines of this (replace ‘content’ with your instance name):
content._x = Stage.width/2;
Then put the same line in the resize listener as well.
thanks Rob. Proportional background scaling and centering the content unfortunately doesn’t seem to work out here, but I guess we’ll better keep this for another tutorial
Regards
Hi Rob
Do you have plans to do a tutorial for this script being used in an array or for externally loaded images?
Many Thanks
Hey Ron,
I may eventually put this together, I’m not sure exactly when at the moment. Apologies! Things are fairly busy right now.
Hi Rob,
I did it with one of my pictures and it sems like is working fine. However when I go test it or publish it as HTML preview doesn`t show up full browser. Any idea why?
it has to do with your Publish Settings. Go to the Publish Settings pane under File, click on the HTML tab, and set the dimensions to 100% height and 100% width
Hi Rob,
This is a great tutorial. I am trying to make a design website that’ll be full-browser. I want to make the portfolio images full screen…similar in concept to Brook-Pifer.com. So I was wondering if there was an easy way to tweak this tutorial to make each portfolio image full screen and scale properly like you’ve done. Thanks for your time.
- Minh
Hi Minh,
That is definitely possible with the sizing algorithm in this tutorial (it appears they are using something very similar), but it is not a simple change - that is significantly more functionality. You should be able to find a clickable gallery tutorial someplace and apply my sizing algorithm to it, however. I don’t know if that helps.
Worked just perfectly!!! Thank you.
Hi Rob, thanks for this - great tutorial. Forgive me if this is a total newbie question - but how would I add a preloader to this?
Dylan,
There are lots of preloaders already written out there. This should work fairly well with any of them. You will probably have to just copy all the frames from this movie into the preloader file
Firstly thanks for the tutorial, site now has it’s home in favourites. I’ve been using different scripts over the last few days to scale a background image, but I ran into problems with content placed over the background, ie a new layer or scene, images (jpgs) placed on the scaled background themselves got scaled and became extremely distorted.
Have you ever come across this problem before? We need to use alot of different jpg images whilst allowing for a liquid scaling stage, but the jpg issue is a serious problem at the moment.
Richard, I’m not sure I understand your question.
Thanks Rob!!! Great tut, exactly what i needed! Thanks for sharing! I’ll try this later.
Hi rob, what if i´ll loading dynamically the photo and the registered point is en left-top corner ? how can i fix the position of the picture?
Hey Andy, in the code where it says “center picture on stage”, change it to say:
pic._x = 0;
pic._y = 0;
and then do the same within the listener as well.
The proportional scaling looks a little weird with that registration IMO, but it works.
Hi, Rob
What size - in pixels - is the picture of the Jaguarundi and how big is your stage in Flash?
Thank you
great tutorial
really really helpful
Bernardo,
Pixel size doesn’t really matter since it dynamically resizes based on the size of the browser, but it’s a good idea to use something big enough for at least a 19″ monitor or so… I think that pic is about 1500px wide. Stage size is completely irrelevant, because in order to be full browser flash, you need to set the flash file to 100% width and 100% height when you publish it. This line:
Stage.scaleMode = “noScale”;
makes the stage size dynamic without changing the size of the elements within the stage.
hi rob, great tutorial.
i was thinking of using this as part of my photography portfolio website
however i am trying to loads my photos in dynamical a button
my problem is that the picture centers on stage but to the top right hand corner of the image
i saw the response about
pic._x = 0;
pic._y = 0;
but im not keen on the way it resizes
is there a way to keep it resizing the original way but loaded dynamicaly?
im guessing its something like
pic._x = Stage.width / 2 - picWidth /2;
pic._y = Stage.height / 2 - picHeight /2;
but im not skilled enough in actionscript to work it out properly
thaks
sorry i cant type today
“trying to load my photos dynamicaly using a button”
and
it centers to the TOP LEFT of the image and the center of the stage
hope thats a bit more clear
thanks again
Close! Try this:
pic._x = Stage.width / 2 - pic._width /2;
pic._y = Stage.height / 2 - pic._height /2;
picWidth and picHeight are actually poorly named calculations of the ratio of the width to height, and vice versa. pic._width and pic._height are the actual height and width.
…your a saviour
thats great
thanks a lot
Hey Rob
as other have said great tutorial.
I have been looking for the Basic structure for a little while now
and only finding much more elaborate explanations which server to only further confuse.
Maybe you or someone could help me with my specific task
which if I am not mistaken you have laid out all the pieces to the puzzle in this tutorial but I think I am missing something.
What I am needing to do is have the background rescale to an image just as you have
But
I also want a movieClip instance centered with proportional scaling.
(so I can have a picture slideshow component load and play images and have the whole browser window in proportion with itself
I believe this should be a simple task
but it alludes me…
any light on this subject would be greatly appreciated.
thanks
shawn - this tutorial actually already centers and scales a movieClip (it’s called ‘pic’). Just replace the picture inside it with your content and it should work fine.
Rob-
wow that was quick.
but I think I miss-asked the question
or am just still doing something wrong.
I want the “other” mc to scale proportional
but not fill the screen.
so I have 2 scaling objects
your background which fills the screen
and the slideshow mc which stays centered and scales proportional but does not fill the screen.
I have gotten close but still no cigar.
thanks again
Ah, I see. You would need to set up another if statement, but do the calculation using a percentage of the stage size. Something like this (this is calculating 50% of the stage size):
slideHeight = new Object ();
slideHeight = slideshow._height / slideshow._width;
slideWidth = new Object ();
slideWidth = slideshow._width / slideshow._height;
if (((Stage.height / Stage.width)/2) < slideHeight) {
slideshow._width = Stage.width/2;
slideshow._height = slideHeight * (slideshow._width/2);
} else {
slideshow._height = Stage.height/2;
slideshow._width = (slideWidth/2) * slideshow._height;
};
I haven’t tested that, so don’t hold me to it, but it would be something along those lines.
Hi Rob,
Thank you for such a great tutorial!
I’m trying to centre elements on the stage, like Frank, but the elements only centre when the screen is manually resized. What’s missing from this code… (’oval’ is the new element)
//set stage for FBF
Stage.align = “TL”;
Stage.scaleMode = “noScale”;
//define dynamic aspect ratios
picHeight = new Object ();
picHeight = pic._height / pic._width;
picWidth = new Object ();
picWidth = pic._width / pic._height;
//conditional statement to account for various initial browser sizes and proportions
if ((Stage.height / Stage.width) < picHeight) {
pic._width = Stage.width;
pic._height = picHeight * pic._width;
} else {
pic._height = Stage.height;
pic._width = picWidth * pic._height;
};
//center picture on stage
oval._x = Stage.width/2;
pic._x = Stage.width / 2;
pic._y = Stage.height / 2;
// create listener
sizeListener = new Object();
// make listener change picture size and center picture on browser resize
sizeListener.onResize = function() {
if ((Stage.height / Stage.width) < picHeight) {
pic._width = Stage.width;
pic._height = picHeight * pic._width;
} else {
pic._height = Stage.height;
pic._width = picWidth * pic._height;
};
oval._x = Stage.width/2;
pic._x = Stage.width / 2;
pic._y = Stage.height / 2;
}
//add listener to stage
Stage.addListener(sizeListener);
oval._x = Stage.width/2;
Thank you!!
Hi Frank,
Your code seems to be correct, so I’m guessing the issue has to do with how you have your instances set up. Unfortunately, I can’t see the rest of the file, so I don’t know what to tell you.
If you want to post a link to your source files, I’ll take a look at it when I get a chance.
-Rob
Hi Rob,
I have come across your post over the last couple of days after months of searching for this solution
However I need the code to pick from a selection (3 or 4) images randomly. I guess this is possible but not sure how.
Thanks in advance
Matt
Hi Rob,
I downloaded your source files, and I noticed that there’s 2 HTML files… one named: FRYEWILES-fbf-scale.html and the other: index.html. The first one doesn’t look full screen, but the second one does.
I tried your tutorial and my HTML file looks like your first HTML file (not full screen). How do I make it look like your index.html file?
Thanks in advance,
Ken
Matt: Actionscript 2 has a Math.random() feature that you should be able to use. You should be able to find documentation for this on Adobe’s support section.
Ken: You need to change your Publish settings. Go to File > Publish Settings, click on the HTML tab, and then for Dimensions use Percent and set it on 100% Height and Width
Hi Rob,
Thanks for the quick response. I changed the setting as you told me to, but still doesn’t appear full screen.
I was wondering why in your source files you have two HTML files, one that looks full screen and the other that doesn’t? I’m asking you this because my HTML file looks exactly as your FRYEWILES-fbf-scale.html file, no full screen image.
Maybe I’m missing one last step?
Ken
Hey Ken,
I just double-checked my source files, and I didn’t include a file called FRYEWILES-fbf-scale.html. I’m guessing you generated this when you Published the movie in Flash. Regardless, take a look at the index.html file. You will notice a couple things - the width and height on the object and embed tags are set to 100%. Also, I have a style tag in the head with CSS to remove the browser default margin, so that the flash movie goes all the way to the edge.
Hi Rob,
Great tutorial! Is there a way i can set a minimum reduction size so that if the browser window is reduced below a certain size the browser will have scroll bars.
Thanks in advance
Chris
Rob,
Just incase you are unclear about what I am asking here is an example of it in action http://www.uniqlo.jp/uniqlock/
Thanks again
Chris
Hi Chris,
That is actually handled through JavaScript, not flash. You can also do it with CSS using the minwidth and minheight properties, but internet explorer has trouble with that method.
If you want to see how uniqlo.com did it, view the source of that page you linked to me. You will see a link in the head to a javascript file in the head called window.js (http://www.uniqlo.jp/uniqlock/js/window.js).
Thanks Rob, I havent had a chance to see if I can get that working as yet but will let you know how I get on. JavaScript is totally alien to me but presumably I will need to create a link in the html to a source file where I will define the minimum settings in the same way Uniqlock have done?
Chris
Yup, that’s pretty much exactly the process! Good luck.
Hi Rob,
That works fine, thanks a lot for your help.
Chris
Hi Rob,
Thanks for the informative tutorial! I was just wandering how to adapt the code so that:
A) The image never gets cropped when scaling the browser window. (I know this will sometimes leave dead space around the image and that’s fine for my purpose)
B) Once the image is at 100% original size it stops scaling above, but when the browser is reduced again the image will once again scale down accordingly.
Any help you can be for that problem would be fantastic! Many thanks!
Jon
Just so you don’t waste your time, I’ve come up with a solution to both problems. Anyway, thanks for setting me on the right heading and I just wanted to say that your blog is really interesting! Great topics.
All the best
Jon
Hey Jon,
Glad we could be of service, and thanks for the compliments! Good luck with your project.
Hi Rob,
firstly great solution! works a treat and is now my method of choice.
I’m having a slight problem though when using it with a fullscreen function, activated via button like this:
on (press) {
if (Stage["displayState"] == “normal”) {
Stage["displayState"] = “fullScreen”;
} else {
Stage["displayState"] = “normal”;
}
}
It seems to cause problems with the loading, especially if you have toggled between fullscreen and normal browser viewing.
Is there any issue you think that could possibly be affected by the fullscreen function above? I’m not after a fix, although if you have one that’s great! I’m more after some guidance about how to perhaps tackle fixing the problem.
many thanks in advance,
James
Hey James,
I honestly haven’t played around with displayState much, and these days most of my time is spent in AS3. That said, my feeling is there is something wrong with your conditional. Adobe has some OK documentation on displayState that may help: http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002149.html
Hello Rob!
And thanks for this great tut.
I have a similar problem than Jon had (in which he came up a solution himself)
But can you show how to modify the original code to so that:
(quotes from Jon)
“A) The image never gets cropped when scaling the browser window. ” -and keeps it’s aspect ratio.
“B) Once the image is at 100% original size it stops scaling above, but when the browser is reduced again the image will once again scale down accordingly.”
I’ve been searching weeks for an answer to this &
I would be more than happy if you could help a flash-rookie like me
Thanks a lot anyways!
-Onny
Hey Onny,
Sorry if this isn’t the most useful answer, I’m a little swamped today. Anyway, look at the conditional statement - it compares the ratio of height to width of the picture to the ratio of height to width of the stage (or vice-versa). You would need to add a conditional statement that takes the original measurements of the photo, and doesn’t let the scaling happen if the stage is bigger than that size.
If I get a few minutes in the next couple days, I’ll try to work up a tutorial for what I am talking about, but in the meantime, try playing with the conditional statement - all the syntax you need is in there already.
Hi Rob.
Thanks for the quick answer!
It would be really awesome if you could do a tutorial for this matter!
I’ll try to play around with the code like you said while waiting if you can get some freetime..
- Onny
Hi Rob,
Firstly let me say thank you for an awesome tutorial, its bt far and away the best I’ve seen online. And thanks also for taking the time to answer peoples questions as well, very decent of you!
I’m having a slight issue and was wondering if you have a quick fix.
I had everything working perfect in AS2 but the project that I am doing at the moment is in AS3. I tried to simply change over to as3 but I got many compiler errors, essentually for every occasion _height or _width was called. I had changed all of these over to displayObject.height and displayObject.width .
When i run the debugger i get..
TypeError: Error #1010: A term is undefined and has no properties.
at FIRSTLIQUIDas3_fla::MainTimeline/frame1()[FIRSTLIQUIDas3_fla.MainTimeline::frame1:8]
Anyway, Ive taken up a bit of your time but I had just noticed that you said that you are now using actionscript 3 so I thought i’d ask if you knew what I should do.
Thanks a million
Hey Alan,
There are a number of syntax changes required to get this to work in AS3:
1) you no longer use the preceding underscore in x, y, height, width, alpha, etc values
2) the addListener method no longer works, you now must use an addEventListener on the stage. This syntax is quite a bit different.
3) Stage.width and Stage.height are now written stage.stageWidth and stage.stageHeight
4) Stage.align and Stage.scaleMode are now stage.align and stage.scaleMode
A lot of the syntax changes in AS3 were made to make the language more consistent. It’s a little annoying migrating code, but it’s for the better in the long run.
I’m going to make a new post based on this one that covers the process in AS3, give me a few minutes…
Ok, Alan, I updated the tutorial for AS3 as well. Good luck!
[...] time back I wrote a tutorial about doing proportional image scaling in full broswer flash. This post is, by far, the most popular single post on the Frye / Wiles blog, and we have gotten [...]
Rob,
You are a true gent. thanks so much for an uber quick response. I managed to get it working and was just coming back to post how I did it but ive been “Postally Piped”.
Keep up the good work buddy!
Thanks again
Hi I am trying to implement a slideshow like in
http://www.pixelwaynyc.com/ with an AS3.
I am loading a pictures from XML within apicture_holder which I want to be centered on the page. Could you pls explain me how they are done that?
Hey Jim,
XML integration is beyond the scope of this tutorial - it is a whole other tutorial in itself. I’ll eventually write that one too, but in the meantime you might check out http://www.gotoandlearn.com or http://www.kirupa.com
Hi Rob,
I see your point….and you are right it rather complicated matter. However I am only interested in the pattern which is used in this site … And especially ..
1)Do they use an general mc holder so the can resize the site proportionally?
2) how do they manage to show vertical and horizontal photos in their slideshow… I mean then I try to do so I always get an landscape photo shown behind portrait
Hey Jim,
Not trying to be difficult, but to be honest I am not sure exactly what technique they used. There are many ways to accomplish almost anything in Flash, and by only seeing the front end of the site there is no way for me to know how they structured their actionscript. For that matter, there is no way for me to know what you are doing in your actionscript either. I know more or less how I would construct a site like that if I were going to do something like that, but again that’s the subject of a whole other tutorial.
Thanks, will try to figure out my self:)…Everyday learning something new.
Your tutorial helped me a lot.
By the way why do you calculate the proportion manually and not using “pic.scaleY or pic.scaleX”?
great script, only problem is i need it to work with an xml driven photogallery and i get it working but because the movieclip is empty the registration point comes top left and the image therefore comes in the middle, i tried various way of changing registration point. is this script revamped to work with external loaded images??? or anyone have an idea how to solve it
Have you tried changing the math to accommodate the different registration point?
Something like this:
pic._x = (Stage.width / 2) - (pic._width / 2);
in AS3 it would look like this:
pic.x = (stage.stageWidth / 2) - (pic.width / 2);
And then do the same thing for Y
Hi Rob,
Just want to say, THANKS MAN! Honestly.
I was searching for ages, some people were even requesting cash
for their samples. And here it is for FREE. Top MAN indeed.
We need more like you.
Also, the script is perfect!
YOUR A LEGEND!
–
Digi
Ha ha ha…. thanks Digi. I’m just trying to help out. Remember to do the same with your flash work, we’re all better off if we share knowledge.
Hi Rob
Your a life saver !!!
Just one question is there a way of setting a minimum image size say 1024×768?
Hey Julian,
Probably the easiest way to do this is to use the browser instead of flash. CSS properties min-width and min-height will work on non-ie browsers. You can use an IF IE statement and a little scripting to handle the rest. Check out the source on this site we did to see one approach: http://www.prvcypremium.com
The other way to do it would be to use a conditional statement in your Actionscript that would only scale width if greater than 1024, and 768 for height.
Hi Rob
Thanks for your help man you’ve saved me hours of slog.
Just a question about how to position a mc within the browser so it stays on the right whatever size the browser is.
The same as float: left: in CSS but with AS 3.0.
Ive tried everything !!!!
But can’t sort it !!!
Thanks Again
Julian
Sorry that should have been float:right;.
Play around with the part of the code that centers the pic on the stage (see above). Right now it is positioning the pic at Stage.width/2, which is the middle. For the left, use 0; for the right, use Stage.width.
You have got the only TRUE Full Browser Script that worked. Everyone else has fail miserably. Wish I found u 2 weeks ago…
Thanks!
[...] http://blog.fryewiles.com/design/07-…-browser-flash [...]
Hey Rob great tutorial! It’s really nice to see that you’ve kept up with everyone’s questions for this long. I was wondering if you ever had a chance to write a guide up for adding images externally to the AS2 script?
Hey Bryon,
While this is something I have done many times, I haven’t had a chance to write a tut for it. At this point I’m moving things to AS3, so I doubt I’ll be doing any more AS2 tutorials. However, any XML tutorial should work - check out http://www.kirupa.com, they have some excellent resources
thanks I’ll find a good xml tut on kirupa that can be added to your image scaling code
Hi Rob,
Great tut! i was looking for this kind of tut for a week now.
I have question:
If i’m gonna use 200×200 image in here. how could i center it on stage?
Thanks in advance.
Just get rid of the part of the code that does the scaling, and it should work just fine. You’re basically just setting the x and y to stage width/2 and stage height/2 (which is the middle). Don’t forget to reflect your changes in the listener.
hi rob, thanks for this wonderful tut. really great!
Anyway, I just need your help with this kind of scaling http://2rmd.com/fire/ I just want to do exact scaling like this e-book. I’m just wondering if you could help me to do that.
THanks in advance
hmmm. what i mean is, i will only start at 200×200 movieclip. and then, when you resize the screen, it will scale. can i do that?
Klautu, it should be exactly the same, except you are calculating size only part of the stage width and height - so in AS2, something like
image._width = Stage.width - 100;This will base your size on the stage width minus 100 pixels. You would also multiply a percentage (Stage.width * .9) and get a similar effect
See my reply to Klautu. Also, you could take out the initial scaling and just leave it in the listener.
Hi again,
I want to show you something. I want this e-book to have some background in it at least 5 pixels border from it. just wondering how can i do that with your code.
I noticed this file code, has this “.setSize” i think this is just for component.
pls do check the files.
http://2rmd.com/download/pageflip.zip
hi Klautu,
I’m apologize, I don’t have time to go through that pageflip code and figure out what they did. However, if you experiment with my suggestion above, I think you will find it will do what you are looking to do.
hi Rob,
It’s ok, I just want to be able to adopt that kind of scaling using your code. But i can’t figure it out. What i just wanna do is to have a bg shape under on that e-book.. Just like scaling them both. But ofcourse different code. Do you think your code, can adopt exact scaling like the pageflip?
Hey Klautu,
The instruction I’ve provided above should be enough to do what you are looking for. If you are having trouble still, you may want to pick up an actionscript book and go back to the basics a bit before finishing your project. Good luck!
thanks very much, i was using swfobject to embed, and found i had to style the page with css in order to get it to work properly (for those familiar with swfobject for embedding)
basically:
html {
height: 100%;
overflow: hidden
}
#yourflashdivid {
width: 100%;
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
and this is with dynamic publishing. if you dont do this styling, youll get a blank page.
hi.
i am fiddeling around with your as3 version.
Your fla is simple however when i copy the code from the actions frame into a new fla and place the nice little cat (instance name pic) into a second layer the compiler trows error:
1120 access of undefined property: picHeight
1120 access of undefined property: picWidth
as far as i can see the fla’s are identical whats happening here?
TIA
It’s because you have strict mode on and my code is a little sloppy from porting it over from AS2. I’ve updated the file to reflect these changes.
Change this:
//define dynamic aspect ratios
picHeight = new Object ();
picHeight = pic.height / pic.width;
picWidth = new Object ();
picWidth = pic.width / pic.height;
into this:
//define dynamic aspect ratios
var picHeight = pic.height / pic.width;
var picWidth = pic.width / pic.height;
Hi Rob,
You may remember that I posted a question some time ago and you very kindly put the code into as3 for me.
Everything is spot on and working fine but I have stumbled upon a problem that my newbie action script brain can’t handle.
I know that you are a busy man but after posting in as.org and other sites to no avail, i thought i’d ask you good self and plead for some of your knowledge.
What I’m trying to achieve:
I am using your script to resize a gradient mc which I am using as a sky bg in my forthcoming site. My content which sits on top of the bg_mc is held in one mc (content)and consists of all of my sections. When buttons are pressed the content slides into place (which was hidden of stage)into the centre of the stage using the tween class.
All this works well but my problem is that I have a foreground mc which is docked on its y axis at the bottom of the stage but i would like to move it slighlty along with the content_mc to create a depth effect. If your having trouble picturing what im trying to do 30 secs in on this video shows you…
http://www.lynda.com/home/Player.aspx?lpk4=47956
To the crux:
Is it possible to have an element resize in accordance with the browser window but not be using 100% of the stage.. ie to have my foreground mc to be the correct ratio to the sky, but have it so that i still have say 25 % off each side of the stage so that I can apply a tween to it to move on its y axis left to right?
I’m so sorry that this has turned into a bit of an essay but I hope you know what i mean ?
Again, i’m totally sorry to be coming back to you again with questions but im really stuck.
Thanks a million and best wishes from Scotland!
Hi Alan,
try setting up an additional conditional statement and an additional dynamic aspect ratio calculation for your second picture, and then use a multiplication of the stage size (in this case I’ve gone 125% of the stage size by multiplying by 1.25).
You would use something like this:
//define dynamic aspect ratios
var secondPicHeight = secondpic.height / secondpic.width;
var secondPicWidth = secondpic.width / secondpic.height;
//conditional statement to account for various initial browswer sizes and proportions
if ((stage.stageHeight / stage.stageWidth) < secondPicHeight) {
secondpic.width = stage.stageWidth*1.25;
secondpic.height = secondPicHeight * secondpic.width;
} else {
secondpic.height = stage.stageHeight*1.25;
secondpic.width = secondPicWidth * secondpic.height;
};
Note: This code has not been tested!
hi Rob,
Thanks for this wonderful tips. I have a question regarding this tut. I saw your image is bigger than your document size in Flash. Is it ok to do that? Will it increase the final size? I am doing a website that I need an intro with several images rotating at the beginning but it ended up with the huge size file. What will you recommend for the format when I import those images to the flash. I saved my images as a jpg file.
The other problem I encountered was the website got cut off on the top and bottom after I brought it to the dreamweaver. It doesn’t show the whole site from the browser. I can only see the middle part of the site. Do you know what cause that happen? any solutions for that?
Thank you in advance
Making the image bigger will increase the final size. Making it too small will result in it being scaled up on larger monitors. You will have to make a call on which size monitor you think it the middle ground, but if it were my site I would probably optimize for 1280 x 1024.
I don’t really use Dreamweaver, I’m not sure what would be causing that problem.
sorry, it’s me again. Forgot to ask one more question. If my document size is 1024×768 and my image size is bigger than that. How could i center it on stage?
Thanks again.
Thanks a lot for your quick response. I put my swf file into dreamweaver so that i can make an index.html file then upload to the server. Do you make an index.html in the dreamweaver?
Probably easier just to have Flash make the HTML file for you using the Publish settings. If you don’t know how to do this, read the Flash help.
That’s what this script does.
thanks very much. I’ll try that.
Perfect - this is exactly what I need and have wondered how to do this loads of times in the past. Thanks very much!
Hi Rob;
How would I apply this code to my entire swf file? I tried applying it to the fla background movie clip calling it “pic” but it loads the background in the center with all the other elements in my original photoshop layout area (working with a designer). Also would like to discuss consulting re; working in my FLV intro. Thanks.
Joan,
Try placing all your elements inside a movie symbol and then calling that ‘pic’.
To discuss consulting, please use our contact form here: http://www.fryewiles.com/contact/
Thanks Rob; I can’t assign an instance name to the movie clip as I used flash insert movie clip which doesn’t allow me to attach an instance name: w/o the instance name the code doesn’t work. Any ideas? Thanks so much!
correction; I used insert New symbol which doesn’t allow me to assign an instance name.
Thanks,
joan
It’s not gonna work without an instance name!
nice bit of code - good tutorial nice and simple to follow. cheers mate
as3 rocks and even rolls.tween lol
Thanks for this, if i want to center the content on my website with this backgroun, how do i do?
hey when i streach the browser my image is pixel out …………… how to do without pixel out?….. u have any idea………….
Anand - use a higher-res image. If you blow up an image beyond its resolution, it will pixelate.
You could also try using Flash’s image smoothing, but I find it slows things down a lot.
Jonathan,
Same way you center the image - put in in a symbol, and align the symbol to Stage.width/2 and Stage.height/2 (or the AS3 equivalent)
Thanks, I tried that but the scaling went strange then. (When i minimized the window i got two white boxes by each side of the image).
Maybe i did something wrong, will try that again.
This is a wonderful Tutorial. I will be using in the development of a cultural festival site. Thank you for the help.
Hey Rob,
Me again! Listen just to say a big massive thank you for all your help with the prop image scaling on my site.I finally managed to go live!!
Im in the middle of making a blog and I’ll throw some thanks your way on it.
Thanks again
Great tutorial! (you must be tired of hearing that), but I’m having a little problem which some others seemed to have. I want to establish minimum dimensions for the resizing. I used to know how to do it in AS 2.0 (i used a completely different code which worked pretty well) but I’m at a complete loss of where to include the conditional in your AS 3.0 code since I’m just beginning to migrate. I guess it will involve just setting a minimum width, but as I said, I just don’t know how to do it in AS 3.0
Maybe you could point me in the right direction
Thanks,
Hi Alex,
Conditionals are pretty much exactly the same in AS3, it’s the event model that is completely different.
Republic of Code has a pretty decent tutorial:
http://www.republicofcode.com/tutorials/flash/as3events/
Hi Rob this tutorial is great its exactly what i wanted, the only problem im having is for some reason my slideshow wont work, i am using slideshowpro ive converted it to a movie and naming it pic but it will not play…
sorry 4got to mention im using as2
Hi Adrian,
I am sorry, I cannot provide support for slideshowpro. Perhaps you can find some assistance on their messageboards?
Hi Rob
Thanks for the reply i wonder is there any type of other sideshow that may work i could possible use im quite limited with my knowledge of flash…
Adrian, what you are trying to do would probably work better if you wrote your own. There are a number of slideshow tutorials out there, if you understand the level of code in this tutorial, you should have no problem.
Hi Rob i want the background pic (the leopard) as a slideshow of different images playing as resizable to the browser window and have the menu keep its proportions in the centre im no good with code unfortuntly, i copied and pasted this one… id be very grateful for help
Adrian,
I apologize, this request is outside the scope of this tutorial. If you would like to hire us to work on this project, please visit our contact page. Thanks
Rob… you’re my hero.
Hi Rob - I created a full browser video in Flash and published the swf and html from Flash and the video works full browser nicely on PC and Mac. I however wanted to put content over this video background using html/css and the html text I have applied is only visible on Macs. I have looked on PC’s and cannot see the text over the video. I also tried this with your file and couldn’t see the text on PC. I was wondering what the problem/solution could be. you can view my source at http://www.kaceymorrow.com.
Thanks!
Hi Rob - Okay - so I figured it out from another forum that I needed to make the wmode transparent. that worked perfectly. thanks for your help!
Hi Rob,
Firstly this is great, a wonderful bit of code that massively helps the learning curve.
I was wondering if it’s not too much work could you show an example of how this would be structured as an external as file for comparison, i.e. within a package?
Jamie,
The scaling part of the code will be the same, you will just need to make sure you load in all the appropriate classes. I may work up an packaged version of the code in the future
thanks Rob, it’d be greatly appreciated if you got the time.
hey there!
a much easier way would be to use the xscale property for proportional resizing.
example:
mc._height = Stage.height;
mc._xscale = bg._yscale;
no need for the math. hope it helps.
oops:
mc._height = Stage.height;
mc._xscale = mc._yscale;
like that.
to give more info:
put all your flash clips inside the movie clip that proportional scales to the screen it will all scale accordingly.
If your doing it for a device that has a rare height larger than the width reverse it.. can use an if statement..
good?
Hi Rob. This code is amazing it’s exactly what I was looking for. However, my website uses a “horizontal scrolling” technique that use this code: function moveX(targ, xpos, speed)
Where xpos = position of the X coordinate on stage.
I turned my entire scrolling background image into a movie clip, but the “moveX” function doesn’t proportionally re-size according to the browser window, making the horizontal scrolling technique work incorrectly.
Do you know a way around this? Or can you point me in the right direction?
Thank you!!
Felipe, it’s hard to say without seeing all of your code, but my first question would be whether you are accounting for your scrolling function in the event listener for stage resize?
This is horizontal scrolling code: (AS2)
import mx.transitions.Tween;
import mx.transitions.easing.*;
function moveX(targ, xpos, speed)
{
new Tween(targ, “_x”, Strong.easeOut, targ._x, xpos, speed, true);
}
home_btn.onRelease = function()
{
preload(”home.swf”,targ_mc);
//bg_targ_mc._x = 0\\
moveX(bg_targ_mc, -1000, 2)
}
My question is in regards to the function moveX(targ, xpos, speed)… What I meant is that with the proportional resizing code you have, the scroll positions of the scrolling background are off (the xpos doesn’t proportionally resize with the browser window).
I am guessing i need to do something with xpos parameter in moveX, meaning it has to be dynamic so that it can proportionally change based on the users browser. Correct?
However, I don’t even know what I would change and where! If you can help that would be amazing. Or at least point my in a certain direction. thanks!
you need to dynamically calculate the value of xpos within your function instead of passing it as a parameter in your function call. Something like this:
function moveX(targ, speed)
{
var xpos:Number = targ._x - 1000;
new Tween(targ, “_x”, Strong.easeOut, targ._x, xpos, speed, true);
}
home_btn.onRelease = function()
{
preload(”home.swf”,targ_mc);
//bg_targ_mc._x = 0\\
moveX(bg_targ_mc, 2)
}
nice tutorial thanks man
Hey Rob, great tutorial, exactly what I was looking for.
The resize function works perfectly, but some pictures (particularly ones with sharp, definable edges/lines) get distorted.
I was wondering if you knew a way for the images to resize without any artifacts?
take at a look at this site: The images in the background resize and the quality is not compromised in the process.
http://www.marc-austin.com/
thanks
Hi Tim,
Try right clicking on the image in your library. Go to properites. Check “Allow smoothing”. That should take care of it.
Thanks rob for your promt reply!
I found out a way just before I checked back here, you can just add this to the end of the code (as2):
pic.forceSmoothing = true;
that would probably work great for externally loaded images
thanks
Tim
Great tutorial Rob.
However when I try to apply the action script I come across an issue. I want the image to be full screen at all times, but when I publish it in HTML the image is at bottom right of my screen and not fully displayed.
Thank you in advance.
-T.
teo, make sure you set your Flash and HTML Export settings in Flash to be 100% width and height. Alternatively, you can use the HTML file in my tutorial and change the name of the file it’s linking to.
Thanks Rob! You just saved my day!
Cheers!
Thanks Rob that did work, but now although the image is fullscreen it now has a small boarder on the top, left and right side. When I publish a preview as a flash file it displays fullscreen, but when I view it as an HTML it has a small boarder. I do have it the settings set at a 100%, and I tired messing with some of the other settings, nothings seems to affect it; Any suggestions?
Thanks again.
-T.
take a look at the CSS I have in my HTML doc. You’re probably seeing the default margin on the BODY tag
Rob,
Is there a way to apply this script only to the background on intro? I have a background image on intro but not the rest. I don’t want this script affecting the whole website. Do I have to set the HTML setting on Flash to percent instead of match movie even I have set up the html somewhere else? thank you.
Hi Andy,
It is difficult to answer your question without more details. Is your entire site in Flash, or are you asking about making a Flash intro page?
In regards to the HTML setting, all that setting that in Flash does is generate an HTML file with those settings. If you already have it set someplace, that is fine too.
Rob, thanks for the replied.
Yes, The entire website is built in Flash but I exported the swf file into Dreamweaver. What I’m trying to achieve is to have an image for background on the intro page only. The layout is center. When I apply this script to my intro page, it affects the whole layout because now all my navigation align to the top left corner. I only want that full width layout on the intro page only. Hope you understand my question. Thanks
Andy,
How are you setting up your site? Does it use the timeline? Or is it using all actionscript?
Rob,
Other than preloader and toggle fullscreen, everything use timeline in this particular page.
So add in a keyframe where you want the background to be removed, and delete it
Rob,
can you hep with the code? so my registration point is in the middle for the image so I just follow your script instead of using x/y coordinate since it’s not on the left corner right?
Andy,
I am sorry, that is beyond the scope of this tutorial. It sounds like you need a bit more experience with Flash, this tutorial is a little more advanced. I recommend http://www.sitepoint.com, there are a lot of good flash tutorials.
no problem. thx
Hey I’m using the below code to load external images but when I try to add the AS3 Proportional Image Scaling the code just makes the image vanish. Any ideas? Thanks a lot.
var imageLoader:Loader;
function loadImage(url:String):void {
// Set properties on my Loader object
imageLoader = new Loader();
imageLoader.load(new URLRequest(url));
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
}
loadImage(”largeImages/k1.jpg”);
function imageLoaded(e:Event):void {
// Load Image
pic.panning_mc.imageArea.addChild(imageLoader);
}
function imageLoading(e:ProgressEvent):void {
trace(”loading”);
}
Hard to say without seeing what it is that you are trying to resize. You may need to more specifically recast your object as a display object or sprite?
picHeight=pic.height/pic.width;
picWidth=pic.width/pic.height;
I managed to get it working by adding the lines above to the imageLoaded function.
function imageLoaded(e:Event):void {
// Load Image
pic.panning_mc.imageArea.addChild(imageLoader);
picHeight=pic.height/pic.width;
picWidth=pic.width/pic.height;
var smoother_bm=Bitmap(imageLoader.content);
smoother_bm.smoothing=true;
TweenMax.to(pic,0,{alpha:0});
scaleProportional();
}
yeah, that was basically what I was getting at. Nice job!
Thank a lot for the AS3 version of the code. Working great. Got it loading dynamic and smoothing .
Maybe I’ll post my finished site here when I’m done. Thanks again.
No problem man, glad it’s working for you. Post the link when it’s ready, I’d like see it.
The home and k1 - k5 pages are working but the rest of the site is still to come. Check it out. Thanks again for the support.
http://www.designlabwest.com/kxt_web/index.htm
Looks great! Nice job
I wanted to chime in with my thanks for this code, and, of course, ask a question. I am oh so close to getting this to do what I want, but there’s just one problem I have.
I’m trying to limit the background image to stop resizing smaller if the stage is resized less than 1120 px. I can get this to work, but I would like to allow the image to resize larger if the height is over 700 even if the width is less than 1120.
Right now, I can get the image to stop reducing in size, but if the window is tall and narrow, the image won’t fill the height proportionately.
This is my listener code. Can you point me in the right direction?
sizeListener.onResize = function() {
//dont let bkg shrink less than 1120 px
if (Stage.width <= 1120) {
bkg._width = 1120;
bkg._height = 700;
}
else if ((Stage.height / Stage.width) < bkgHeight) {
bkg._width = Stage.width;
bkg._height = bkgHeight * bkg._width;
}
else {
bkg._height = Stage.height;
bkg._width = bkgWidth * bkg._height;
};
bkg._x = 0;
bkg._y = 0;
linkLogo._y = Stage.height - (linkLogo._height + 12);
data_menu_mc._y = Stage.height - (data_menu_mc._height + 15);
Try this:
if (Stage.width <= 1120 && Stage.height <= 700) {
…..
}
&& is the logical And operator
That did it! I knew it was close. Thank you very much.
I thought I would share the code I’ve got in case anyone would like it.
Here’s what it does:
- Resizes the background image, but will limit the minimum width to 1120 (this could be adjusted to whatever)
- Bottom aligns an element (like a menu bar) to the bottom of the screen
- Bottom right aligns another element (like a logo)
//set stage
Stage.align = “TL”;
Stage.scaleMode = “noScale”;
//define dynamic aspect ratios
bkgHeight = new Object ();
bkgHeight = bkg._height / bkg._width;
bkgWidth = new Object ();
bkgWidth = bkg._width / bkg._height;
//conditional statement to set minimum height and width
if (Stage.width > 1120) {
bkg._width = Stage.width;
bkg._height = bkgHeight * bkg._width;
} else {
bkg._height = bkg.height;
bkg._width = bkg.width;
};
//keep bkg top left
bkg._x = 0;
bkg._y = 0;
//align menu to bottom
data_menu_mc._y = Stage.height - (data_menu_mc._height + 15);
//align logo to bottom right
linkLogo._y = Stage.height - (linkLogo._height + 12);
linkLogo._x = Stage.width / 1.05 - _root.linkLogo._width / 1.05;
// create listener
sizeListener = new Object();
// make listener change bkgture size on browser resize
sizeListener.onResize = function() {
//dont let bkg shrink less than 1120 px
if (Stage.width <= 1120 && Stage.height <= 700) {
bkg._width = 1120;
bkg._height = 700;
}
else if ((Stage.height / Stage.width) < bkgHeight) {
bkg._width = Stage.width;
bkg._height = bkgHeight * bkg._width;
}
else {
bkg._height = Stage.height;
bkg._width = bkgWidth * bkg._height;
};
bkg._x = 0;
bkg._y = 0;
linkLogo._y = Stage.height - (linkLogo._height + 12);
linkLogo._x = Stage.width / 1.05 - _root.linkLogo._width / 1.05;
data_menu_mc._y = Stage.height - (data_menu_mc._height + 15);
}
//add listener to stage
Stage.addListener(sizeListener);
Hello,
Great tutorial!!
Im using exactly what Gino modified on Oct 29. How and where do I put in the code a maximum bg height restriction?
Thanks,
Steve
Steve,
You would put it near the minimum height conditional
I modified gino’s code to AS3… still working on bg maximum restriction. Am I on the right track?
function sizeListener(e:Event):void {
//dont let pic shrink less than 950 px
if (stage.stageWidth <= 950 && stage.stageHeight = 1425 && stage.stageHeight >= 940) {
pic.width = 1425;
pic.height = 940;
}
else if ((stage.stageHeight / stage.stageWidth) < bkgHeight) {
pic.width = stage.stageWidth;
pic.height = bkgHeight * pic.width;
}
else {
pic.height = stage.stageHeight;
pic.width = bkgWidth * pic.height;
};
pic.x = 0;
pic.y = 0;
I dont think I copied the correct code… here it is…
function sizeListener(e:Event):void {
//dont let pic shrink less than 950 px
if (stage.stageWidth <= 950 && stage.stageHeight = 1425 && stage.stageHeight >= 940) {
pic.width = 1425;
pic.height = 940;
}
else if ((stage.stageHeight / stage.stageWidth) < bkgHeight) {
pic.width = stage.stageWidth;
pic.height = bkgHeight * pic.width;
}
else {
pic.height = stage.stageHeight;
pic.width = bkgWidth * pic.height;
};
pic.x = 0;
pic.y = 0;
hi,
when i publish the source file and try opening the html version in a web browser, it doesn’t perform the way it should. the image becomes smaller and doesn’t fill the background. please help to resolve this.
thanks.
Hi Sid,
Take a look at the CSS I have in the HTML file I provide
hi Rob,
Thx for the code. flash is new for me…
I tried your code and it is working but I still have a little border all around my pix…So, its not using all the space of the browser, compare to your jaguar.
Don’t know where is my mistake…so I dare to ask your advice. Many thanks. alex
Alex,
Check out the CSS in the sample HTML doc I included - by default, the body tag has some margin on it, you need to zero that out.
Thank you very much for your help Rob.
Was the HTML…It works!!!
Thanks!
Rob, i must say: i’m not gay, in fact i have a girlfriend, but i love you. hahahahahahahahaha!
thank you sooo much for this!!! i’ve been cracking my head these last few days, because i’m not a programmer, i’m a designer that likes Flash a lot, and i’ve been trying to figure this out.
i still didn’t get eeeeeverything in your code, i’ll take a better look at it on the next days, to really understand it, but man, it works!!
thank you very much, it’s the least i could say!
best!
Hey Paulo,
It’s ok man, we accept all people here at Frye / Wiles
Glad the code worked for you!
Hi Again Rob,
Just a quick question about using css to maintain a minimum browser window size.
I have been throught the previous comments and managed to get your work around half working for the PRVCY site. My problem is that width works fine but I am having a problem with the behaviour of the height as it seems to pull up the contect on resize. The problem actually exists on that PRVCY site as well.
Do you have any idea as to what is causing this effect.
Many thanks Rob
The problem actually has to do with the CSS properties of min-height and min-width not being fully supported by all browsers (ahem…IE!). On PRVCY, we made an assumption (perhaps incorrectly?) that people don’t generally have really short, wide browser windows. We dealt with width sizing in IE by using a little line of javascript inside an IE conditional comment that adjusts clientWidth. I can’t remember why we didn’t do clientHeight as well, but I’m guessing we tried it and it cause some undesirable result. You can see this if you view source on the PRVCY page.
Hi Again Rob,
Do you have any idea as to how to fix this. The problem these days is of course pesky mobile phones.
I have never really touched css before so I am toiling to work out where to turn next.
Thanks again
Alan
Hello Rob,
I have used your text to try and simulate the scale listener, in conjunction with an array and a button, to change the image in the movie clip. To no prevail. I am at a very basic level but assume there is some conflicting code? if anyone could take a look and point it out to me it would be much appreciated!!
’site’ is simply a folder holding my images, and ‘box’ the movieclip where i would like the image to change. Which it does when the button is clicked. Only the scale doesnt work in any respect. This is the code…
stage.align = “TL”;
stage.scaleMode = “noScale”;
//
var imageList_array:Array = new Array(”back.JPG”, “back2.JPG”);
var imageToLoad:Number = 0;
//
var image_mcl:MovieClipLoader = new MovieClipLoader();
image_mcl.addListener(mclListener);
image_mcl.loadClip(”site/”+imageList_array[imageToLoad],box);
//
boxHeight = new Object ();
boxHeight = box._height / box.width;
boxWidth = new Object ();
boxWidth = box._width / box.height;
//
if ((Stage.height / Stage.width) <boxHeight) {
box._width = Stage.width;
box._height = boxHeight * box._width;
} else {
box._height = Stage.height;
box._width = boxWidth * box._height;
};
box._x = Stage.width / 2;
box._y = Stage.height / 2;
//
sizeListener = new Object ();
//
sizeListener.onResize = funtion(); {
if ((Stage.height / Stage.width) <boxHeight) {
box._width = Stage.width;
box._height = picHeight * pic._width;
} else {
box._height = Stage.height;
box._width = boxWidth * box._height;
};
box._x = Stage.width / 2;
box._y = Stage.height / 2;
}
Stage.addListener (sizeListener);
//
this.load_btn.onRelease = function() {
imageToLoad++;
if (imageToLoad == imageList_array.length) {
imageToLoad = 0;
}
this._parent.box.loadMovie(”site/”+imageList_array[imageToLoad]);
};
You dont know how much I would appreciate anyone solving this for me
Si
ok, fixed notable things like accidently leaving in code like pic and the occasional ; in the wrong place, but still no luck!
nor does my clip align top left, despite the publish settings and the code starting off that way
help!!!!
ok, forget everything i said i fixed it and my array/scale works. thanks very much to the initial blog post!! I removed code that centers the image and set x & y to 0
but, i still have a problem
when the site is opened the first image is full size/zoom (bigger than the frame) and the resize only changes this when the window/browser is resized… then it works fine. Anyone know whats up with that?
do i have to apply an onLoad or onEnterFrame or something?
again. help very much appreciated.
Si
Hi Si,
You can probably just set your initial sizing directly in actionscript. Or you could make a little function with that code and then run that function. You don’t really need to have an event attached to it. Take a look at my AS3 code above - see the centerPic function (and how I subsequently run it at the end)? Same concept.
Glad it’s working for you!
Hi Rob,
still having trouble working this out.
when it loads the image scales up and only changes when you actually resize it. unlike ur example. mine is exactly the same only with an array to load images into the movieclip onrelease of a button. any thoughts?
thanks for help. tutorial was great also
Hey Rob I am trying to do the scaling but for a flv player. The scaling code doesn’t react the same when applied to a flv player instance and I was wondering if you ever played with that?
Anyone ever play with trying that? I tried the default flv player in AS3 with no luck.
Oh and the original web site I was working on is done, I even have the background images panning though its pritty processor heavy. :S Check out http://www.kainaluxt.com. Thanks again.
Hi DeltaFrog,
Yeah, FLV player reacts a bit different. For standalone player situations, I recommend publishing as an AIR file instead.
So I would be changing the movie format to AIR? Forgive my ignorance. I don’t know much about AIR.
Would I still be able to use the default FLV player I am used to skinning?
Hi Delta,
I’m sorry, I misread your original post. For some reason, I was thinking you were referring to the desktop flash player.
Anyway, for FLV, there are a whole other set of parameters. I suggest taking a look at the FLVPlayback class on adobe’s help docs: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
If this isn’t an urgent thing, I will probably be writing a tutorial on this subject in a couple months, because we have an upcoming client job that deals with the same kind of thing.
Hope that helps!
Hey no problem thanks for the advice. Its urgent so I really need to find a solution right away. Is it just a syntax issue? Do I need to use different code for the scaling? Thanks in advance.
Yippy! Ok so I got it working by changing the scaleMode in the component inspector. If you use exactFit its all groovy.
I just need to add smoothing too the video now.
And for anyone who also wanted smoothing of pixels:
var videoPlayer:VideoPlayer = flv_player.getVideoPlayer(flv_player.activeVideoPlayerIndex);
videoPlayer.smoothing = true;
Thank you!!!!!!!!!!!!!!!!!
Awesome, you just saved me some time!
Hey Rob, quick question..
Is there a way to make it so if the users only resizes the bottom of the browser, the top portion of the movie clip / image stays in place, only cropping out the bottom?
Currently it does a combination of moving, and cropping bottom and cropping top as you move the bottom of the browser up..
http://blog.fryewiles.com/wp-content/examples/fbf-scale/
Notice as you resize your browser upward, the cat’s head gets pushed behind your search bar, way out of view at the top. I’d rather have the top of the image stay put, and just have the bottom being cropped out as you resize the bottom of the browser to the top..
like on http://www.jimcarrey.com, the top for the most part always remains in view, and doesn’t get pushed out of view.
Hopefully I didn’t confuse you with my question, thanks
Actually I figured it out for myself, to do what I had said.
I simply aligned the symbols center point with the top center point of the image.
And changed the values of:
//center picture on stage
function centerPic():void {
pic.x = stage.stageWidth / 2;
pic.y = 0;
}
Worked like a charm
Thanks again for the great code!
Hi Rob,
I have a small problem.
I have a movie clip showing a masked area of five images. I just want to resize the masked area whic is 20% of the width and 33.333% of the height of the total movieclip. How would I write the code to do that?
Thx.
Hi Joakim,
Not sure exactly how to answer that question, it is pretty vague. But you are probably going to want to try someting like:
mask.width = (movieclip.width * .2)
Ok maybe I was a little vague.
I will try to explain again.
I have five 7 images placed next to eachother inside a movieclip in the shape of a lying capital T.
When pressing a button the images inside the mivieclip tweens on the x and y axel.
To prevent all the images of showing I have a mask that is the same size as one of the images w:1280 x h:649.
My wish is for this scaling script that you have posted works on only the masked area.
The total width of the image is 1280×649 and the movieClip is 6400×1947.
Is this possible to do?
Thx
Joakim
Hi again, I am still in need of help on the last post but I have one more. Is there a way to get a scroll x and y on the part of the image outside the screen when rezized?
Thx,
Joakim
Hi Joakim,
I’m afraid that is quite a bit out of the scope of this tutorial. A quick web search should get you to some scrollbar tutorials, and then it should just be a matter of applying some conditional sizing to those elements.
I understand it is taking this tut a little bit further but I would say it is very related. I understand you might not have the time. How about my first question. Proportionally scale onle part of a movie clip How would I do this?
I have tried setting the
var picHeight = pic.mask_mc.height / pic.mask_mc.width;
var picWidth = pic.mask_mc.width / pic.mask_mc.height;
But that is to no help. Well it seems to be on the right track but is scales unproportionally. Any direction you can give me?
Please help me I cannot seem to get it to work. As I have been trying to explain I am trying to proportionally scale a movieclip containing content five times the width and three times the height then I want to fit on the sceen. I want to just fit the visible content fullscreen and the rest needs to be scaled even further out. Can you please help me?
Hi Joakim,
I’m sorry, I really don’t have time to help everyone troubleshoot their flash project. My best recommendation is to go to Actionscript.org or some other Flash user community and see if someone on a message board has the time. Sorry!
understood
Hey Rob
looks great, i’m actually trying to do this with an external swf, a al http://www.yeticycles.com/#/features/, see the way the external swf maintains its aspect ratio when the browser is resized. could this code do such a thing?
Many thanks for your help
Hey k4rlos,
Yeah, that will work. The methodology is the same, just apply the state properties and scaling stuff to the external swf as well. We did this on http://www.prvcypremium.com
Wow thanks for your quick reply, thats exactly the functionality i need, i have been tearing my hair out for a bit. i’ve got your source files so will now have a go..
Ah didn’t read that as well as i thought… what properties would i need to add to the external swf..
Hey Rob,
I have so far implemented your code with less than a few hiccups, how ever there are a fews snags i’m hoping that you can help me out on..
when i first publish the site, the external swf that is being loading in comes in huge until i resize.. second when it finally does fit on resize the swf is forced into the width and height… weird huh..
If this is too much to ask then any help would be great..
Many thanks in advance
Set up your external swfs exactly like above. Make sure you are setting initial properties as well as having properties change in the event listener.
Hi Rob,
I have a question. I have a movie clip with 7 images in it. My document size and images are both 1300*860. The final swf size is huge and it takes forever to load it. I am trying to make the final swf size a lot smaller. Do you know if I can make my image files smaller but keep the fla document size as 1300*860? Or any other way that i can have big images but with smaller size? P.S i am using AS2
Many thanks Rob
Hi Slee,
You could use a preloader to load these in individually. Or you could use more jpg compression on the image to bring the file size down.
Thank you for your quick response!
I have a preloader in my fla file but still very slow due to the size. For the images, I already compressed them but still about 700 kb each. You mentioned i could use a preloader to load the images individually. Do you know how? How does it work?
Thanks again.
Here’s a tutorial on something similar: http://www.kirupa.com/developer/actionscript/moviecliploader.htm
Thank you for the link. I’ll check it out.
Hi Rob
can you learn me the action of script??
mingo
Rob- thank you and well done. Your guide worked like a charm- you really have been a big help to a lot of people.
After reading through a lot of the comments, I am curious after reading Gino’s info on rescaling down to a certain image size. Using AS3, what is the most efficient way to limit the downsize scaling for a pic such as 1024×768? Would it be better to define a new function, or add into the scaleProportional function? I did play around with some code for quite some time but gave up as I could not get it to work smoothly or to the correct scaling.
Any input would be most appreciated and utilized as it would be nice to limit the downsize scaling in similar situations.
Hi Mitch,
you would simply need to add an additional conditional statement into the resize function will halt the scaled based on the stage.stageWidth and stage.stageHeight
Thanks again Rob- I really appreciate the help. I successfully added the additional conditional statement and have posted it here in case anyone else wanted to see the code in AS3. The background image was dcpic_mc. I did notice I had to adjust the width and height to match the proportions of the picture. It would be nice to figure out a more automated way to calculate the correct scale in case someone wanted to make a background slideshow. Of course, they images can all be adjusted in photoshop to have the same scale anyway. I also included a simple ‘annoying’ round circle tween as an extra- I will be changing that one shortly, I just wanted to make sure tweening worked with the code I used. Thanks again Rob!
import fl.transitions.Tween;
import fl.transitions.easing.*;
stage.addEventListener(Event.RESIZE, resizeListener);
stage.addEventListener(Event.RESIZE, sizeListener);
stage.scaleMode = “noScale”;
stage.align = “TL”;
var picHeight = dcpic_mc.height / dcpic_mc.width;
var picWidth = dcpic_mc.width / dcpic_mc.height;
var xTween:Tween;
var yTween:Tween;
function resizeListener (e:Event):void {
xTween = new Tween (ball_mc, ‘x’, Elastic.easeOut, ball_mc.x, (stage.stageWidth / 2), 1, true);
yTween = new Tween (ball_mc, ‘y’, Elastic.easeOut, ball_mc.y, (stage.stageHeight / 2), 1, true);
}
function scaleProportional():void {
if ((stage.stageHeight / stage.stageWidth) < picHeight) {
dcpic_mc.width = stage.stageWidth;
dcpic_mc.height = picHeight * dcpic_mc.width;
} else {
dcpic_mc.height = stage.stageHeight;
dcpic_mc.width = picWidth * dcpic_mc.height;
};
}
//minimum size you want- define height and width to prevent deadspace
function minSize():void {
if (stage.stageWidth <= 800 && stage.stageHeight <= 530) {
dcpic_mc.width = 800;
dcpic_mc.height = dcpic_mc.width*picHeight;
};
}
//place picture on stage
function topleftPic():void {
dcpic_mc.x = 0
dcpic_mc.y = 0
}
// make listener change picture size and center picture on browser resize
function sizeListener(e:Event):void {
scaleProportional();
topleftPic();
minSize();
}
//run initial locations and size
scaleProportional();
topleftPic();
minSize();
Mitch,
Thx for ur post. Ive been hv issues with this tutorial wherein the img would show up somewhere in the middle and out of the screen. By using ur code below-
//place picture on stage
function topleftPic():void {
dcpic_mc.x = 0
dcpic_mc.y = 0
}
i got it to work.
However, while the image is scaling to the correct browser width, im not getting to see the entire image within the browser height. The img im using in fla is 4752 x 3168. My screen resolution is 1920 x 1200. Shld i not be seeing the entire img scaled down to the 1920 x 1200 and filled in the browser?
Pls advise. Thx
regds
Rob- thx for the initial post….
thanks a lot for your tut, its way more simple that my script, this it gonna help me a lot, thank you.
exactly what i was looking for after searching for a bit and only finding full screen examples this is a god send.
cheers
- pheyonagh
Thank you very much!!! Perfect!
[...] Creating liquid GUIs with Flash and ActionScript 3.0 | Adobe Developer Connection Proportional Image Scaling in Full Browser Flash | Frye / Wiles Blog have fun
__________________ http://www.socreative.tv flash / web / motion / [...]
Thanks for the great tutorial. It works fine for me! But, i have a question. What if I want to use a uiloader component instead of a picture in the swf? I’ve tried it, but the picture appears 1/4.
Hi STP,
I have no experience with the UI Loader component. This may help - http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/containers/UILoader.html
Thank you so much for your help - I needed that AS3 code badly :-)))
This was exactly what I was looking for. Thank you sooooo much!
STP, I had the same trouble. I used the UIloader to load images randomly.
Make sure you use:
pic.x = (stage.stageWidth / 2) - (pic.width / 2);
+ same for y. That seemed to help but the image would only scale when the browser size changed – not when it initially loaded. To overcome this I added an ENTER_FRAME listener with the same code as the resize listener. This fixed initial scaling problem but now there’s a slight frame flicker as the code snaps the image to fit within the browser.
See my site (work in progress) here:
http://lukemorgandesign.com/
If anyone has any ideas on how to fix the background intial frame flicker I’d love to hear about it.
By the way Rob, you are a legend!
lol… I don’t think I can accept that title yet Luke
To scale the pic form the center stage the following with help.
function centerPic():void {
pic.x = stage.stageWidth - pic.width/2 - stage.stageWidth/2;
pic.y = stage.stageHeight -pic.height/2 - stage.stageHeight/2;
}