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()
{
      super();
   }
}

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;
   myImage.setImage(path);

   return myYmage;
}

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

   if(container != null)
   {
      container.layout();
   }
}

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

Advertisements

My dev blog

I write a lot of code. I do it at my job by day, and I do it for side projects at night. I work on a wide variety of projects, for different platforms, in different programming languages.

My favorite way to learn how to do new things is to search the internet and find someone else who has done it before. Why reinvent the wheel, right? It never occurred to me until now that I should probably be posting my own stuff too – hopefully other developers can get something out of it, plus its good reference for me, too.

So that’s what this blog will be. Random musings and things I’ve learned about programming. Enjoy!