Are you new? Read the FAQ and catch up on!
1k views

Check if a pixel is transparent in a DisplayObject

Very useful when detecting clicks on bitmaps with transparency.

ActionScript 3
  1. /**
  2.  * Checks if a specific pixel is transparent in a <code>DisplayObject</code>
  3.  *
  4.  * @param point Global (stage) coordinates of the pixel to check
  5.  *
  6.  * @return True if the pixel is transparent
  7.  */
  8. public function isPixelTransparent(object:DisplayObject, point:Point):Boolean
  9. {
  10.     // If object is a BitmapData we can use directly the hitTest function
  11.     if(object is BitmapData)
  12.     {
  13.         return !(object as BitmapData).hitTest(new Point(0,0), 255, object.globalToLocal(point));
  14.     }
  15.     else
  16.     {
  17.         // If the "bounding boxes" don't collide, we can return false directly
  18.         if(!object.hitTestPoint(point.x, point.y, true))
  19.         {
  20.             return false;
  21.         }
  22.         else
  23.         {
  24.             // object was not a BitmapData so we have to copy the pixels to
  25.             // a new BitmapData and we use the hitTest function
  26.  
  27.             // This is a bit tricky because we can not assume that the
  28.             // object regpoint is in (0, 0). So, we need to ensure we keep
  29.             // the regpoint in the new BitmapData.
  30.             var rect:Rectangle = object.getBounds(null);
  31.             var bmapData:BitmapData = new BitmapData(rect.width, rect.height, true, 0x00000000);
  32.  
  33.             var matrix:Matrix = new Matrix();
  34.             matrix.translate(-rect.x, -rect.y); // This is what corrects the regpoint when copying pixels
  35.  
  36.             bmapData.draw(object, matrix);
  37.  
  38.             var isTransparent:Boolean = !bmapData.hitTest(new Point(rect.x, rect.y), 0, ct.globalToLocal(point));
  39.  
  40.             bmapData.dispose(); // Not sure if this is required...
  41.  
  42.             return isTransparent;
  43.         }
  44.     }
  45. }
  46.  

­

Tags: ActionScript 3.0 BitmapData

Embed: