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

  1. 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.
  2. 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.
  3. 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.
  4. Do all the attached DisplayObjects and the AutoFitArea need to share the same parent?
    Yes.
  5. 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.
  6. 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});
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.

Author: Jack Doyle
Copyright 2011, GreenSock (This work is subject to the terms here.)

  • Twitter
  • Facebook
  • Digg
  • StumbleUpon
  • del.icio.us
  • Yahoo! Buzz
  • Google Bookmarks
  • RSS
  • LinkedIn
  • Reddit

Comments (24) RSS

Posted by Bart on February 17, 2010

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?)

Posted by Shawn Makinson on February 17, 2010

Jack, you have a great view into what we all will find useful. Thanks for your continued work on such great projects!

Posted by admin on February 17, 2010

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.

Posted by chris manlapid on February 17, 2010

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!

Posted by admin on February 17, 2010

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);

Posted by Rodrigo Robledo on February 17, 2010

MUITO UTIL!!! GREAT!

Posted by iwan on February 18, 2010

thanks for the great class. finally i can throw away my own browser window background image class.

Posted by sitron on February 18, 2010

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?

Posted by admin on February 18, 2010

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.

Posted by arno on February 21, 2010

GREAT again!

thanx a lot jack

Posted by thibaud on February 22, 2010

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)

Posted by admin on March 6, 2010

Great idea thibaud. I just added that feature via a new “crop” parameter in the attach() method.

Posted by Martin on April 19, 2010

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 ;)

Posted by admin on April 19, 2010

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.

Posted by sascha on May 14, 2010

Thanks so much for LiquidStage! You made my Day with this fantastic Tool.

Best regards
Sascha

Posted by Yoshiyan on May 17, 2010

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

Posted by admin on May 17, 2010

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.

Posted by Lucy on November 12, 2010

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 :)

Posted by Jack on November 12, 2010

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).

Posted by Lucy Minshall on November 13, 2010

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

Posted by Adam J on February 1, 2011

One on the most useful tools i have ever seen. Great stuff, thanks for sharing:)

Posted by Clark on May 1, 2011

This really is excellent. A++

Posted by ACJ on August 8, 2011

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?

Posted by Jack on August 8, 2011

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.

To download the code, you must agree to the following license:

"NO CHARGE" NON-EXCLUSIVE SOFTWARE LICENSE AGREEMENT
-----------------------------------------------------------------------------
PLAIN ENGLISH SUMMARY:

  1. You may use the code at no charge in commercial or non-commercial apps, web sites, games, components, and other software as long as end users are not charged a fee of any kind to use your product or gain access to any part of 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 end users are charged a usage/access/license fee, please sign up for a "Business Green" Club GreenSock membership which comes with a comprehensive commercial license. See http://www.greensock.com/club/ for details.
  2. Use at your own risk. No warranties are offered.
  3. Please respect the copyright.

-----------------------------------------------------------------------------

LEGALESE:

This is a legal agreement between you (either an individual or a single entity) and GreenSock, Inc. ("GREENSOCK") for the proprietary GreenSock code known as TweenLite, TweenMax, TweenNano, TimelineLite, TimelineMax, and other copyrighted code that is available for download at http://www.greensock.com (this code and documentation, as well as any updates which may at GREENSOCK's sole discretion be provided to you from time to time, are referred to in this Agreement as "PROGRAM"). By downloading, copying, or otherwise using the PROGRAM, you agree to the terms and conditions of this Agreement. If you do not agree to the terms and conditions of this Agreement, please do not download or use the PROGRAM.

I. LICENSE
A. Subject to the terms and conditions of this Agreement, GREENSOCK hereby grants you a non-exclusive, worldwide, non-transferable right to use the PROGRAM in apps, web sites, games, components and other software applications ("Developed Works") for which the end user is NOT charged any fees. If you would like to use the code in a commercially licensed Developed Work for which end users are charged a fee (either for usage or access), simply sign up for the appropriate "Business Green" Club GreenSock membership at http://www.greensock.com/club/.

II. LIMITATION OF LICENSE AND RESTRICTIONS
A. You agree that you will not sell, rent, or license the PROGRAM's source code or any derivative works thereof to any third party without the prior written consent of GREENSOCK. Distribution of the PROGRAM as part of your Developed Work is acceptable so long as it is used exclusively as a part of your Developed Work. You agree not to modify or delete GREENSOCK'S existing copyright notices located in the source code.

B. You may use, duplicate, and distribute the compiled object code as embedded in Developed Works created by you, either for your own use or for distribution to a third party so long as end users of the Developed Work are not charged a fee for usage of or access to any portion of the Developed Work. Please see http://www.greensock.com/licensing/ for descriptions of Developed Works that qualify for the "No Charge" license.

C. You may make modifications to the source code exclusively for your own use in order to perform bug fixes or other minor edits required to operate the PROGRAM as originally intended.

III. CONSIDERATION
A. The license rights granted to you under this Agreement are at no charge, but only in the following circumstances: If on your own behalf or on behalf of a third party you incorporate the PROGRAM into a web site, app, game, program or any component thereof (collectively, "Developed Work"), which in the case of a web site, must be accessible to internet users without payment of a fee of any kind, and in the case of a software application, game, program or component, neither you nor anyone to whom you distribute the Developed Work charges a user a fee of any kind to use such Developed Work or application, game, program or component into which such Developed Work is embedded. The foregoing shall apply regardless of whether you are paid to create such Developed Work.

B. In the event your intended use of the PROGRAM does not meet the criteria for the "no charge" license rights set forth in the immediately preceding paragraph, then you are not licensed to use the PROGRAM under this Agreement and must license the PROGRAM under GREENSOCK'S separate fee-based Software License Agreement which is granted to "Business Green" Club GreenSock members (see http://www.greensock.com/club/ for details).

C. You may make modifications to the source code exclusively for your own use in order to perform bug fixes or other minor edits required to operate the PROGRAM as originally intended.

IV. TITLE AND OWNERSHIP
A. The PROGRAM is licensed, not sold, and is protected by copyright laws and international treaty provisions. You acknowledge that no title to the intellectual property in the PROGRAM is transferred to you. You further acknowledge that title and full ownership rights to the PROGRAM, including all intellectual property rights therein, will remain the exclusive property of GREENSOCK and you will not acquire any rights to the PROGRAM except as expressly set forth in this Agreement. You agree that any copies of the PROGRAM you make will contain the same proprietary notices which appear on and in the PROGRAM. You agree that GREENSOCK may identify you as a licensee unless you make a written request otherwise. GREENSOCK hereby grants to you the right to disclose that your product, game, software application, component, or other Developed Work makes use of GREENSOCK code (for example, "Powered by TweenLite").

V. DISCLAIMER OF WARRANTY AND LIMITATION OF LIABILITY
A. THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. GREENSOCK DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE PROGRAM WILL MEET YOUR REQUIREMENTS OR THAT OPERATION WILL BE UNINTERRUPTED OR ERROR FREE. GREENSOCK shall not be liable for special, indirect, incidental, or consequential damages with respect to any claim on account of or arising from this Agreement or use of the PROGRAM, even if GREENSOCK has been or is hereafter advised of the possibility of such damages. Because some states do not allow certain exclusions or limitations on implied warranties or of liability for consequential or incidental damages, the above exclusions may not apply to you. In no event, however, will GREENSOCK be liable to you, under any theory of recovery, in an amount in excess of $250. Notwithstanding anything else in this agreement, you agree to indemnify GREENSOCK, its assignees, and licensees, and hold each of them harmless from and against any and all claims, losses, damages, and expenses, including legal fees arising out of or resulting from any negligent act or omission by you.

B. GREENSOCK may, at its sole discretion, provide support services related to the PROGRAM, but has no obligation to do so.

VI. TERMINATION
If you at any time fail to abide by the terms of this Agreement, GREENSOCK shall have the right to immediately terminate the license granted herein and pursue any other legal or equitable remedies available.

VII. MISCELLANEOUS
A. This Agreement shall be construed in accordance with the laws of the State of Illinois. In the event of any dispute between you and GREENSOCK with respect to this Agreement, we both agree that if we cannot resolve the dispute in good faith discussion, either of us may submit the dispute for resolution to arbitration with the American Arbitration Association before a single arbitrator using the AAA Rules for Commercial Arbitration. The arbitrator's decision is final and can be enforced in any court with jurisdiction over such matters.

B. This agreement represents the complete and exclusive statement of the agreement between GREENSOCK and you and supersedes all prior agreements, proposals, representations and other communications, verbal or written, between them with respect to use of the program. This agreement may be modified only with the mutual written approval of authorized representatives of the parties.

C. The terms and conditions of this Agreement shall prevail notwithstanding any different, conflicting, or additional terms or conditions which may appear in any purchase order or other document submitted by you. You agree that such additional or inconsistent terms are deemed rejected by GREENSOCK.

D. GREENSOCK and you agree that any xerographically or electronically reproduced copy of this Agreement shall have the same legal force and effect as any copy bearing original signatures of the parties.

Copyright 2006-2013, GreenSock, Inc. Updated 2012-08-28

I'd like to learn how to get bonus plugins, update notifications, SVN access, and more.
To continue, you must agree to the following license: