Monday, April 19, 2010

Export Release Build-Reduce File size in Flex

Problem
How to reduce SWF size in flex?

Solution
When preparing a Flex project for deployment, always make sure to export a release build. I think most people know about this feature of FlexBuilder, but I'm not sure everyone is aware of just how important it is. The SWF that is generated when you run or debug your project contains a lot of extra byte code used for debugging and profiling your content.
This extra byte code has a very obvious effect on the size of your SWF (adding over 35% in some cases). It also has a less immediately obvious (but no less significant) effect on the performance of your application. In one sample, a 980kb SWF was reduced to 675kb, and some performance intensive code ran over 2.5x faster in the release build than in the debug version.
Never deploy a project without exporting a release build, and be sure to test a release build if you are experiencing problems with file size, performance, or memory utilization.

Rounded Corner Image in Flex

Problem
By default, the mx:Image component does not allow rounded corners.

Solution
                 Extend the mx:Image component to handle rounded corners by using a mask. You could also try extending other components, i.e. a Canvas, and it will also work. I have a couple projects where I round off a Canvas, and place items in it to achieve a certain look.

Usage:
<RoundedImage source="someImage.jpg" width="250" height="250" cornerRadius="15"/>
Source:
package com
{
 import mx.controls.Image;
 import mx.core.UIComponent;
 
 public class RoundedImage extends Image
 {
  protected var roundedMask:UIComponent;
  protected var cornerRad:int;
  
  public function RoundedImage()
  {
   super();
  }
  
  public function get cornerRadius():int
  {
   return cornerRad;
  }
  
  public function set cornerRadius(radius:int):void
  {
   cornerRad = radius;
  }
  
  override protected function createChildren():void
  {
   super.createChildren();
   
   this.roundedMask = new UIComponent();
   this.addChild(roundedMask);
  }
  
  override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
  {
   super.updateDisplayList(unscaledWidth, unscaledHeight);
   
   roundedMask.graphics.clear();
   roundedMask.graphics.beginFill(0x000000);
   roundedMask.graphics.drawRoundRectComplex(0, 0, unscaledWidth, unscaledHeight, cornerRad, cornerRad, cornerRad, cornerRad);
   roundedMask.graphics.endFill();
   
   this.mask = roundedMask;
  }
 }
}