AutoFitArea – Stretch/Scale/Position DisplayObjects to Fit Within a Rectangular Area
- Version: 2.54, Updated 2011-04-26
- Compatibility: AS3 (Flash Player 9 or later)
- File size added to compressed SWF: about 3.5kb
AutoFitArea allows you to define a rectangular area and then attach() DisplayObjects so that they automatically fit into the area, repositioning and scaling/stretching in any of the following modes: STRETCH, PROPORTIONAL_INSIDE, PROPORTIONAL_OUTSIDE, NONE, WIDTH_ONLY, or HEIGHT_ONLY. Horizontally align the attached DisplayObjects left, center, or right. Vertically align them top, center, or bottom. AutoFitArea extends the Shape class, so you can alter (and yes, tween) the width/height/scaleX/scaleY/x/y properties of the AutoFitArea and then all of the attached objects will automatically be affected. Attach as many DisplayObjects as you want.
When you attach() a DisplayObject, you can define a minimum and maximum width and height. AutoFitArea doesn’t require that the DisplayObject’s registration point be in its upper left corner either. You can even set the calculateVisible parameter to true when attaching an object so that AutoFitArea will ignore masked areas inside the DisplayObject (this is more processor-intensive, so beware).
To make visualization easy, you can set the previewColor to any color and set the preview property to true in order to see the area on the stage (or simply use it like a regular Shape object by adding it to the display list with addChild(), but the preview property makes it simpler because it automatically ensures that it is behind all of its attached DisplayObjects in the stacking order).
For scaling, AutoFitArea alters the DisplayObject’s “width” and/or “height” properties unless it is rotated in which case it alters the DisplayObject’s transform.matrix directly so that accurate stretching/skewing can be accomplished.
There is also a LiquidArea class that extends AutoFitArea and integrates with LiquidStage so that it automatically adjusts its size whenever the stage is resized. This makes it simple to create things like a background that proportionally fills the stage or a bar that always stretches horizontally to fill the stage but stays stuck to the bottom, etc.
Interactive demo
Documentation
Please view full ASDoc documentation here.
Sample AS3 code
//import the GreenSock classes
import com.greensock.layout.*;
//create a 300x100 rectangular area at x:50, y:70 that stretches when the stage resizes (as though its top left and bottom right corners are pinned to their corresponding PinPoints on the stage)
var area:AutoFitArea = new AutoFitArea(this, 50, 70, 300, 100);
//attach a "myImage" Sprite to the area and set its ScaleMode to PROPORTIONAL_OUTSIDE and crop the overspill
area.attach(myImage, {scaleMode:ScaleMode.PROPORTIONAL_OUTSIDE, crop:true});
//if you'd like to preview the area visually, set preview to true (by default previewColor is red)
area.preview = true;
//attach a CHANGE event listener to the area
area.addEventListener(Event.CHANGE, onAreaUpdate);
function onAreaUpdate(event:Event):void {
trace("updated AutoFitArea");
}
//to create an AutoFitArea exactly around a "myImage" DisplayObject so that it conforms its initial dimensions around the DisplayObject, use the static createAround() method:
var area:AutoFitArea = AutoFitArea.createAround(myImage);
FAQ
- Where do I get the code?
AutoFitArea is included in the main AS3 GreenSock download zip – just click the “Download AS3″ button at the top right corner of this page. AutoFitArea is in the com.greensock.layout package. - Does the registration point of each attached DisplayObject need to be in its upper left corner?
No, the registration point can be anywhere. AutoFitArea uses the object’s bounds and could care less about the registration point. - Does AutoFitArea change the stacking order or container heirarchy of attached DisplayObjects?
No, not at all. The only things it changes about attached DisplayObjects are the x/y/width/height (depending on the ScaleMode). It respects their placement in the display list. - Do all the attached DisplayObjects and the AutoFitArea need to share the same parent?
Yes. - What if my attached DisplayObject contains masked objects – can I make AutoFitArea only concern itself with the visible content?
Sure, just set calculateVisible:true in the vars parameter of the attach() or createAround() method (it’s false by default). This is more processor-intensive, though, so only set calculateVisible to true when absolutely necessary. - What if I want an attached object to use custom bounds (like if certain parts of it should not be factored in to its overall size when fitting it into the area)?
You can define a DisplayObject (typically a child of the attached object) as the customBoundsTarget in the vars parameter of attach() or createAround(). For example, if parentBox contains box1, box2, and box3 arranged horizontally, but you only want box2 (the center one) to fill the AutoFitArea, you’d do myArea.attach(parentBox, {customBoundsTarget:parentBox.box2, scaleMode:”proportionalOutside”, crop:true}); - If I manually move or resize/reposition an attached DisplayObject, how can I make the AutoFitArea update and reapply its constraints?
Simply call the update() method. - Does AutoFitArea require LiquidStage?
Absolutely not. It can be used independently and has no dependencies on LiquidStage. There is, however, a LiquidArea class that extends AutoFitArea and it integrates with LiquidStage. - How do I install the class? Do I have to import it on every frame?
Please refer to the “getting started” page. It “installs” just like any of the tweening classes. - Can I tween the dimensions and position of the AutoFitArea?
Of course. That’s one of the great conveniences of AutoFitArea. Feel free to use TweenLite/Max/Nano to tween the width, height, scaleX, scaleY, x, or y properties of your AutoFitArea instance. You should not, however, tween the x/y/width/scaleX/scaleY properties of the attached DisplayObjects because doing so would cause the tween to fight with AutoFitArea for control of those properties. You can always release() any attached DisplayObjects so that AutoFitArea no longer controls them. - Do I have to purchase a license to use this code? Can I use it for commercial purposes?
You may use the code at no charge in commercial or non-commercial web sites, games, components, applications, and other software as long as end users are not charged a fee of any kind to use your product or gain access to it. If your client pays you a one-time fee to create the site/product, that’s perfectly fine and qualifies under the “no charge” license. If multiple end users are charged a usage/access/license fee of any kind, please simply sign up for a corporate Club GreenSock membership which comes with a special commercial license granting you permission to do so. Click here for details. Club GreenSock members get several useful bonus plugins, classes, update notifications, SVN access, and more. Please see the licensing page for details on licensing.
Need help?
Feel free to post your question on the forums. You’ll increase your chances of getting a prompt answer if you provide a brief explanation and include a simplified FLA file (and any class files) that clearly demonstrates the problem.
Comments (24)

Good stuff, looks very usefull. Does it support DisplayObjects that have their registration point somewhere else then top-left? (like in the center or somewhere outside it’s actual content area?)
Jack, you have a great view into what we all will find useful. Thanks for your continued work on such great projects!
Sure, Bart, AutoFitArea works great with objects that don’t have the registration point in the upper left corner. It uses their bounds. Thanks for bringing this up, though – I added the answer to the FAQ section.
Thank you for very useful plugin. I was just thinking if we could use a display object as the AutoFitArea. Then it popped into my head that you could pass that display object’s x, y, width and height into AutoFitArea!
Sure, Chris, and don’t forget that there’s a createAround() static method that will do it for you.
var area:AutoFitArea = AutoFitArea.createAround(myDisplayObject);
MUITO UTIL!!! GREAT!
thanks for the great class. finally i can throw away my own browser window background image class.
the idea is really good! Thanks for sharing!
wouldn’t there be a way to have the same kind of functionalities but without extending Shape?
I can see how convenient the predefined shape methods are, but it might be more optimized to keep it abstract.
What do you think?
Sitron, the great thing about extending Shape is that it allows not only easy visualization (which can be super helpful during development at least) but also usage of advanced stuff like localToGlobal(), globalToLocal(), hitTestPoint(), etc. Heck, you could even use TransformManager on it to make the whole thing interactive, but none of that would be possible if I abstracted it. I don’t think there’s much of a performance tradeoff either since you can turn preview off and take it out of Flash’s graphics rendering queue. I’m certainly open to other ideas/suggestions, though.
GREAT again!
thanx a lot jack
another very useful tool. looks great!
what about adding a masking option -probably only useful for the PROPORTIONAL_OUTSIDE mode though- via a scrollRect maybe.(masks can be problematic when gettingBounds of masked objects)
Great idea thibaud. I just added that feature via a new “crop” parameter in the attach() method.
I dont understand what the new CROP-paramater is for. I am stupid and would probably need it to be more documentet, all other modes are obvious for me though
Martin, the crop parameter is for when you want to have any attached object be cropped by the AutoFitArea. So for example, maybe you attach() an object using the PROPORTIONAL_OUTSIDE ScaleMode which could make the edges exceed the size of the AutoFitArea – if you set crop to true, it will crop the object (by applying a mask) so that you can’t see the overspill.
Thanks so much for LiquidStage! You made my Day with this fantastic Tool.
Best regards
Sascha
Can it work well in Flex? I have a try, but it seems that it will not work if I apply the option corp = “true”,
Best regards
Yoshiyan
Yoshiyan, Flex requires that only objects that extend UIComponent can be added to the display list (well, at least that’s the general rule). AutoFitArea extends Shape, as do the masks that it creates when you set crop=true, so Flex burps. You should be able to easily solve this, though, by changing the “Shape” references in the class to UIComponents.
This is such a fantastic tool!
I’m currently creating an application for users to upload and image then scale it, move it, then save the new image.
AutoFitArea is great as when the image uploaded, regardless of size it scales the image to the defined area.
My only issue is, when the image is saved, it saves it at it’s original scale, not the scale from the AutoFitArea.. Is there anyway to set the scale that the AutoFitArea has applied, to be the new default scale of the attached display object?
Thanks
Lucy, it sounds like you’re just saving it incorrectly – are you using BitmapData.draw() or something? Remember, that always gets rid of all transformations unless you utilize the “matrix” parameter. That has nothing to do with AutoFitArea though.
If you need interactive scaling/rotating/moving, you might want to check out http://www.greensock.com/transformmanageras3/ (not sure if you saw that already).
Thanks for that, of course I didn’t think about using the matrix parameter, I am indeed using BitmapData.draw() at the moment.
I have seen the transform manager, it’s also a great tool.
I’m actually just scaling the image using a slider and have just used flash’s native components for that.
Thanks again for your help.
Lucy
One on the most useful tools i have ever seen. Great stuff, thanks for sharing:)
This really is excellent. A++
Great tool! Just one question:
Let’s say I’m building a photo gallery for mobile devices (like your panel-scroll example), and when the screen rotates, not only does the image rotate, but scales proportionally, as well.
When using AutoFitArea, do I create one instance and attach multiple pictures (displayObjects) to it, or do I have to create multiple AutoFitArea instances?
ACJ, you can resize and reposition an AutoFitArea anytime and it’ll automatically adjust all the attached DisplayObjects. You can force an update by calling its update() method.




















Download zip