DisplayUtils

We’ve all been there. You’re building an image gallery and you need to create consistently sized thumbnails from a set of images, of various sizes and orientations and with differing aspect ratios – or you need a fullscreen background which always fills the stage, regardless of a user’s screen resolution and browser window size – or maybe you just need to fit a DisplayObject into a rectangular area whilst maintaining the correct proportions of the original image.

Introducing DisplayUtils

Since this is a common task, one that I find myself coding over and over, I’ve whipped up a little class called DisplayUtils which will help with the scenarios mentioned above and more.

The main method in DisplayUtils is FitIntoRect. FitIntoRect can work in several ways. You can use it to resize a DisplayObject to fit inside a rectangle, or you can use it to generate a transformation matrix, which can be applied to an object or used with the BitmapData.draw method to create thumbnail previews, or both. There is also another method called createThumb, which uses fitIntoRect to quickly and easily create nicely cropped and scaled thumbnails from a source image with any aspect ratio.

Have a play with the demo above to see what you can do with these methods.

Using DisplayUtils and fitIntoRect

There are several parameters to control how fitIntoRect works. Here’s what you can pass to the method:

  • displayObject : The DisplayObject to resize
  • rectangle : A Rectangle object representing the space the DisplayObject should fit into.
  • fillRect : Whether the DisplayObject should be transformed to fill the entire rectangle, or whether it should fit completely within it.
  • align : The alignment of the DisplayObject within the rectangle, for example Top Left or Middle.
  • applyTransform : Whether the calculated transformation matrix should be applied to the DisplayObject within the fitIntoRect method. If false, the DisplayObject will not be modified, but the Matrix returned by the fitIntoRect method can be used to transform objects or modify the draw command on a BitmapData object.

The download includes all necessary classes as well as several examples of how to use the fitIntoRect method. Here are some code snippets for getting started with…

Example Usage

Fit a DisplayObject into a Rectangle

var area:Rectangle = new Rectangle( 0, 0, 200, 100 );
DisplayUtils.fitIntoRect( myDisplayObject, area, true, Alignment.MIDDLE );

Create a fullscreen background image

stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

function onStageResized( event:Event = null ):void
{
	var area:Rectangle = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight );
	DisplayUtils.fitIntoRect( myDisplayObject, area, true, Alignment.MIDDLE );
}

stage.addEventListener( Event.RESIZE, onStageResized );
onStageResized();

Create a thumbnail

var thumb:Bitmap = DisplayUtils.createThumb( myBitmap.bitmapData, 100, 100, Alignment.MIDDLE, true );
addChild( thumb );

Download

You can download the DisplayUtils class, as well as the Alignment class, which simply contains enumeration for the various alignment options when using fitIntoRect and createThumb.

A example of some of the uses discussed above is also available in the zip.

Download: DisplayUtils
Posted on 25 May 2009
40 Comments
4 Trackbacks

Meta

Fit DisplayObject into Rectangle was posted on May 25th 2009 in the category Code / Actionscript 3.0, Code, Flash, Open Source and tagged; , , , , .

You can Leave a comment.

Twitter <follow>

February 7th 2012 - 9:13pm

@yizzreel Ha, yeah Twitter isn't the medium for this kind of conversation ;) Thanks for the Watts link, about to press play now...

Discussion

44 Responses to Fit DisplayObject into Rectangle

1 2 3 4

Leave a Reply

Pingbacks / Trackbacks

  1. 2 years ago Classe DisplayUtils by Soulwire | Flash-Square

    [...] Encore une classe très utile, et très bien présentée, sur l’excellent blog de Soulwire : DisplayUtils permet d’afficher une image dans un rectangle défini, en conservant les proportion de l’image, et en paramétrant l’alignement souhaité. En fonction de la taille de l’image, vous pouvez choisir de remplir totalement la zone d’affichage, et donc de cropper l’image, ou bien d’ajuster la taille de l’image au rectangle afin de l’afficher entièrement. Démo, exemple d’utilisation et téléchargement >> [...]

  2. 1 year ago Project is bijna af « Stephanepolet's Blog

    [...] mijn resize-methode aangepast. Deze werkte echt niet naar behoren. Ik maakte eerste gebruik van een DisplayUtil klasse die ik had gevonden op het internet maar deze werkte niet goed voor Bitmaps. Dan [...]

  1. tf 2 years ago

    god bless you

    Reply to this comment

  2. Rob 2 years ago

    So great! Thank you very much for posting this, I’ll give it a shot tonight. Hope things are going well with the move.

    Reply to this comment

  3. fenixkim 2 years ago
  4. Bynho 2 years ago

    Amazing, well done!
    Every post just gets better and better!

    Reply to this comment

  5. Heiner 2 years ago

    Just what I needed! Thank you for sharing! :)

    Reply to this comment

  6. fesilverio 2 years ago

    great! there´s a simple version from this feature in casalib framework, package utils.RatioUtil. But your have some more features. Congratulations, nice job! =)

    Fe 013
    (dev from brazil)

    Reply to this comment

  7. samBrown 2 years ago

    wow, simply awesome! Sincere thanks for sharing.

    Reply to this comment

  8. ROGERLUIZ 2 years ago
  9. rur 2 years ago

    “god bless you”

    I second that

    Reply to this comment

  10. Karl Freeman 2 years ago

    This looks like an amazing class to use, thanks so much for this and all of your contributions.

    Reply to this comment

  11. Valentino 2 years ago

    Thanks for this awesome utility! To thank you I’ve also added a centering function. I’ve been using it a lot and felt it’d be a nice addition. Code is below. Feel free to use it as you wish.

    Cheers!

     /**
    		 * Centers any DisplayObject to another DisplayObject.
    		 *
    		 * @param objToBeCentered
    		 *
    		 * The DisplayObject you want to center.
    		 *
    		 * @param base
    		 *
    		 * The DisplayObject you want to base the centering off of.
    		 */
    		 public static function centerInObj(objToBeCentered : DisplayObject, base : DisplayObject, align : String = "ABSOLUTE")
    		 {
    			 // calculations are made in switch to avoid calculating both width/height diffs if only one is necessary.
    			 var diffWidth = 0;
    			 var diffHeight = 0;
    
    			 switch(align)
    			 {
    				 case "ABSOLUTE":
    				 	diffWidth = (base.x+base.width) - (objToBeCentered.x + objToBeCentered.width);
    					diffHeight = (base.y+base.height) - (objToBeCentered.y + objToBeCentered.height);
    				 	objToBeCentered.x += diffWidth/2;
    					objToBeCentered.y += diffHeight/2;
    				 	break;
    				 case "VERTICAL":
    				 	diffHeight = (base.y+base.height) - (objToBeCentered.y + objToBeCentered.height);
    					objToBeCentered.y += diffHeight/2;
    				 	break;
    				 case "HORIZONTAL":
    				 	diffWidth = (base.x+base.width) - (objToBeCentered.x + objToBeCentered.width);
    					objToBeCentered.x += diffWidth/2;
    				 	break;
    				 default :
    				 	diffWidth = (base.x+base.width) - (objToBeCentered.x + objToBeCentered.width);
    					diffHeight = (base.y+base.height) - (objToBeCentered.y + objToBeCentered.height);
    				 	objToBeCentered.x += diffWidth/2;
    					objToBeCentered.y += diffHeight/2;
    			 }
    		 } 

    Reply to this comment

  12. roberto.guerra 2 years ago

    this is a great tool. thanks

    Reply to this comment

1 2 3 4