I’ve had that exact task numerous time while scripting actionscript. I have a source image loaded externally or a mc within the program and I need to fit it into a certain area (width x height) but keep the aspect ratio the same or as photoshop calls it “constrain proportions”. I’ve done this with fancy and not so fancy formulas and equations, but finally I had it and created a simple function that would do it every time. Figured it was worth sharing cause if I’ve googled it before then others most likely will too!
This is more than just setting the width and height of an object, because that way the image is easily skewed and the natural proportions are messed up. If you want to just use scale you need to know the dimensions of the image being resized, and that’s just not scalable (no pun intended).
What we have to do is to do both. Assign the width and height to skew it, and then scale it to correct the proportion. So if we want to resize an image when we don’t know it’s current size to fit into a 300 pixel square we set the width and height of that image to 300 and then a bit of logic that can be summed up in one line:
1
| mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; |
That says if the x scale is larger than the y scale set the x to the y scale amount, and vice versa. It’s basically setting both scales to the smaller of the two. This works because we don’t know the original size of the image, but actionscript does. scaleX and scaleY are ratios of the current width and height to the originals. A little complicated I know, but that’s why I’ve made the function below. I know how to use it and now I don’t have to think about skewing and then scaling back to keep my aspect ratio or proportion. You should see how to use it just by looking at it:
1
| resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true) |
Pass in the movieClip you want to resize, and the size you want it to fit into. So with the same example above, just do
Example
Here’s an interactive example to show what I mean. It loads an external image and you click and drag the mouse around to resize it. To toggle whether you want to constrain proportions use the space bar. Type a url to any image you want to test it with and press load, or hit ‘enter’.
Here’s a screenshot of me playing with a photo in here NOT constraining proportions.

Source (AS3)
The resizing function
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| //The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{
maxH = maxH == 0 ? maxW : maxH;
mc.width = maxW;
mc.height = maxH;
if (constrainProportions) {
mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
}
} |
The full source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| var defaultUrl:String = "http://blog.circlecube.com/wp-content/uploads/2008/11/circlecubelogo4.png";
var image:MovieClip = new MovieClip();
loadImage();
function loadImage(url:String=""):void {
if (url == "" || url == defaultToLoadString) url = defaultUrl;
//clear image
image.visible = false;
image = new MovieClip();
//add image
var ldr:Loader = new Loader();
var urlReq:URLRequest = new URLRequest(url);
trace("loading image: " + url);
ldr.load(urlReq);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, imageCompleteHandler);
image.addChild(ldr);
addChild(image);
}
function imageCompleteHandler(e:Event):void {
resizeMe(image, stage.stageWidth)
}
//The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{
maxH = maxH == 0 ? maxW : maxH;
mc.width = maxW;
mc.height = maxH;
if (constrainProportions) {
mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
}
}
var constrainOn:Boolean = true;
var isPressed:Boolean = false;
stage.addEventListener(MouseEvent.MOUSE_MOVE, moved);
stage.addEventListener(MouseEvent.MOUSE_DOWN, pressed);
stage.addEventListener(MouseEvent.MOUSE_UP, released);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);
function keyDownListener(e:KeyboardEvent) {
if (e.keyCode == 32){//spacebar
toggled(e);
}
if(e.keyCode == 13){//enter
loadImagePress(e);
}
}
function moved(e:Event):void{
if (isPressed)
resizeMe(image, mouseX, mouseY, constrainOn);
}
function pressed(e:MouseEvent):void{
isPressed = true;
moved(e);
}
function released(e:MouseEvent):void{
isPressed = false;
}
function toggled(e:Event):void{
constrainOn = !constrainOn;
moved(e);
}
var defaultToLoadString:String = "type url of image to load";
toLoad.text = defaultToLoadString;
toLoad.addEventListener(FocusEvent.FOCUS_IN, toLoadFocus);
toLoad.addEventListener(FocusEvent.FOCUS_OUT, toLoadBlur);
function toLoadFocus(e:FocusEvent):void{
if (toLoad.text == defaultToLoadString)
toLoad.text = "";
}
function toLoadBlur(e:FocusEvent):void{
if (toLoad.text == "")
toLoad.text = defaultToLoadString;
}
loadBtn.addEventListener(MouseEvent.CLICK, loadImagePress);
function loadImagePress(e:Event):void{
loadImage(toLoad.text);
} |
Download
constrainProportions.fla
And as usual, let me know if you’ve got any comments questions or suggestions! Thanks,
Fullscreen in AS3 Tutorial | Plus Firefox Flash bug when enter fullscreen keyboard events fired
To view the full fullscreen tutorial go here: How to use fullscreen in AS3 | Stage Display State Tutorial
Sucks when you seem to have a bug in your code somewhere so you dissect your code over and over and are convinced that according to your code, everything should be fine, so you come back later thinking fresher eyes will see it, and still can’t find the cause, and then resort to debugging with various trace statements…
I’ve been developing a custom flash player in as3. Fullscreen and all those bells and whistles… I could test locally and eveything was beautiful… but then upload and test in the browser and when I would go into fullscreen mode, the video would pause. Pretty annoying bug! So I’d go through my code and examine anywhere a call to pause the video (there are only two): pressing the play/pause button and pressing the spacebar (keyboard shortcut). I couldn’t find any correalation. I was thinking adobe must be doing some crazy security things when going into fullscreen… but no, no other video player I’ve seen does this!
After commenting out my keyboard events, the bug is fixed! But I still can’t use the spacebar to pause/play. I love this functionality for usability. Isn’t that pretty standard for video? space to pause, it’s like second nature to me.
Does entering fullscreen really trigger a keyboard event equivalent to pressing my spacebar!? Sure enough. how much sense does that make, but it gets better! I had a friend test this swf and it worked fine for him. No pause on fullscreen! Wha!? Using good ole IE7… So yes, it’s a browser specific actionscript bug, firefox even! That was one of the things I liked about flash initially, not too much to mess with as far as cross browser issues once you get the swf embedded in the html, or so I thought.
So after playing with booleans to try to control when the keyboard events will be working.
Has anyone experienced this or another issue that just left you baffled, even after you figured out the bug?!
Well, I’ve done the right thing, I’ve posted about it to hopefully help anyone else having this issue. I created a test case file to rule out anything else in my code and make sure I’m not crazy.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
stage.align = StageAlign.TOP_LEFT;
fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);
fsb.buttonMode = true;
ssb.buttonMode = true;
onFullscreenChange();
function fullscreenToggle(e:MouseEvent = null):void {
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
onFullscreenChange();
}
function onFullscreenChange(e:FullScreenEvent = null):void {
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
tracer("full screen");
fsb.visible = false;
ssb.visible = true;
}
else {
tracer("small screen");
fsb.visible = true;
ssb.visible = false;
}
tracer("toggle to "+stage.displayState);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);
function keyDownListener(e:KeyboardEvent) {
tracer("keyboard: keyCode: "+ e.keyCode.toString());
}
var tracerwindow:TextField;
function tracer( ...args){
if (tracerwindow == null){
tracerwindow = new TextField();
tracerwindow.width = stage.stageWidth/2;
tracerwindow.height = stage.stageHeight;
tracerwindow.multiline = true;
addChild(tracerwindow);
}
for (var i:uint = 0; i < args.length; i++) {
tracerwindow.appendText(args[i].toString() + " ");
}
tracerwindow.appendText("\n");
trace(args);
}
other places that I’ve found this mentioned that helped me understand what was going on:
http://dreamweaverforum.info/actionscript-3/123202-keyboard-event-full-screen.html
http://bugs.adobe.com/jira/browse/FP-814