Setting image sizes in Actionscript

So I’m not an Actionscript developer. My background is in C/C++/C#, with some Java thrown in for good measure. My UI experience is mainly Silverlight. So, when picking up Actionscript to write an app for the Blackberry Playbook, I’ve learned a few interesting…quirks about the language.

One that caused me to bang my head against my desk for far too long was setting image sizes. Did you know that if you set an image size or scale value before its rendered, that Adobe Air will ignore it, and go with the image file’s size? I sure didn’t.

Considering my application dynamically adds lots of images that are dynamically sized based on various factors, this was a very frustrating issue. For starters – its completely unintuitive. If it weren’t for some random forum post that it took me hours to find (thanks, poster, if I remembered where I read this I’d cite you), I’d never have figured it out. Secondly, with the dynamic nature of applications, its hard to keep track of what the size should be. Here is what I did to solve the issue. I’m not saying its eloquent. I’m not saying its ideal. But, it worked, which is really all I cared about.

1) Create an a class that extends Image, and lets you store the width/height as properties:

import qnx.ui.display.Image;

public class ExImage extends Image
public var storedWidth:int;
public var storedHeight:int;

public function ExImage()

2) Create the ExImage object, set the width/height to the custom fields, and capture the onLoad event, and set the Image’s size there

private function CreateImage(width:int, height:int, path:String) : Image
   var myImage:ExImage = new ExImage();

   myImage.addEventListener(Event.COMPLETE, onImageLoad);
   myImage.storedWidth = width;
   myImage.storedHeight = height;

   return myYmage;

private function onImageLoad(e:Event) : void
   var myImage:ExImage = ( as ExImage);
   myImage.setSize(myImage.storedWidth, myImage.storedHeight);
   var container:Container = myImage.parent as Container;

   if(container != null)

…and that does the trick. Its ugly, it doesn’t make sense why they designed it this way…but there ya go.