Flex: Making Scaled Images Look Better
Posted by David Freerksen at 9:55 AM
0 comments - Categories: Technical Articles | Adobe AIR | Adobe Flex
An instance came up where images were getting loaded into Flex using a service call. Normally this is a rather simple task. The problem was the images that were being loaded in were too large to fit in the designated area. If your Flex application is using absolute positioning then the images might be on top of or below other objects on the screen. If your Flex application uses percentage based positioning, things get pushed off to the side and down creating scrollbars. Simply put, it starts looking visually sloppy. Because of the CMS our client was using, scaling the actual image was not an option because we had no access to build image scaling into the CMS system.
Our only other option was to scale the images using code. The simple solution was to simply set the height and width. Once we did this the images looked jagged and pixelated. In order to fix this we had to apply Bitmap smoothing. Bitmap smoothing doesn’t do a fantastic job, but it is much better than the alternative.
There are multiple ways to do this. I’ll go over two of them. The first method utilizes ActionScript methods inside your application.
var myImage:Image = new Image();
myImage.addEventListener(Event.COMPLETE, lsnr_image_Complete);
myImage.source = "image.jpg";
myImage.width = 50;
myImage.height = 50;
this.addChild(myImage);
private function lsnr_image_Complete(evt:Event):void
{
var bitmap: Bitmap = ((evt.currentTarget as Image).content as Bitmap);
if(bitmap != null)
{
bitmap.smoothing = true;
}
}
The Event.COMPLETE event listener waits and listens for the image to be loaded. Once the image is loaded it calls the method that applies Bitmap smoothing. Very simple and straight forward.
The second method is to use a custom component. Create a new ActionScript class and name it SmoothImage. Inside the file create the following code:
package
{
import flash.display.Bitmap;
import mx.controls.Image;
public class SmoothImage extends Image
{
override protected function updateDisplayList(w:Number, h:Number):void
{ super.updateDisplayList (w, h);
if(content is Bitmap)
{
var bitmap:Bitmap = content as Bitmap;
if(bitmap != null && bitmap.smoothing == false)
{
bitmap.smoothing = true;
}
}
}
}
}
Inside your application file you can now add Bitmap smoothing to the images by using the following code:
<smoothimage source="image.jpg" width="50" height="50">
</smoothimage>
Like I said before, there are many other ways to accomplish this same task. You can also use these methods to scale the image up if you wanted.
Just a quick note, even though you you are scaling the image down, you are still loading in the entire image file. Meaning if you are loading in a 1024x768 image that is 3MB it doesn't matter if you are scaling the image down to 100x100, you are still loading in the entire 3MB for that 100x100 image.
