Check transparency

2019-09-12 03:10发布

问题:

I have swf file(900x600) and main part of that file is transparense. So I want by clicking in swf file know either user clicks on transaprent part of image or not...

I can get mouse coordinates by

event.localX
event.localY

So how to know in clicked part swf is transparent or not?

回答1:

First of all, be sure, that you have some transparent sprite on background of your swf - otherwise you won't receive event.

Second, do not use pure local coordinates, they can contain local coordinates of another inner object, while you need them from root. For example, I've used stage's coordinates

If you receive mouse event, add mouse event listener to the root of that swf and write following:

        var bmd:BitmapData = new BitmapData(1, 1, true, 0);
        var pt:Point = new Point();
        var m:Matrix = new Matrix();

        m.translate(-e.stageX, -e.stageY);
        bmd.draw(this, m);
        var transparent:Boolean = !bmd.hitTest(pt, 0x00, pt);

        trace('color: '+bmd.getPixel32(0,0).toString(16));
        trace('is tranparent? ' + transparent);

        bmd.dispose();


回答2:

You can add an event listener on the stage for a mouse click, and check if e.target == stage. Here is the code:

import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.CLICK, hClick);
function hClick(e : MouseEvent) : void
{
   trace(e.target == stage); // true if we click on the transparent zone, false if we hit a symbol on the stage.
}


回答3:

Not the best or cleanest code but it should work. This is not tested code I just whipped it up.

private function handleMouseDown(event:MouseEvent):void {
  var pt:Point = new Point(event.localX, event.localY);
      pt = event.target.globalToLocal(pt);
  var tmp:int = int( (new uint( event.target.getPixel32(pt.x,pt.y) ).toString(16)).substr(0,2) );

  if( tmp != 0 ){
    trace( 'is transparent' )
  }
}