Creating a hitarea for PNG Image with transparent (alpha) regions in Flex

Unfortunately flex doesn’t take the alpha channel of PNG images for the hitarea into account when using mx.image or Bitmap class. That means that mouse events will trigger even if the mouse pointer is located over a transparent area of the image. Fortunately Flex lets us define a sprite as a custom hitarea for graphical Objects. With a simple method we can create a sprite that covers all non transparent areas of the bitmap image and assign it as a hitarea


private function createHitArea(bitmapData:BitmapData, grainSize:uint=1):Sprite{
	var _hitarea:Sprite = new Sprite();, 1.0);			
	for(var x:uint=0;x<bitmapData.width;x+=grainSize) {
		for(var y:uint=grainSize;y<bitmapData.height;y+=grainSize) {					
			if(x<=bitmapData.width && y<=bitmapData.height && bitmapData.getPixel(x,y)!=0) {,y,grainSize,grainSize);						
	return _hitarea;
Illustration of the effect of the grainSize parameter when using a PNG image

The method lets you define the size of the rectangles (grain size) to save some performance when dealing with large images. The larger the grainSize parameter the less iterations you need to create the Sprite


This content requires Adobe Flashplayer

View Source is enabled