Monday, April 19, 2010

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;
  }
 }
}

No comments:

Post a Comment