Sonntag, 7. August 2011

Images with transparancy as a Simplebutton's hitTestState

I recently came across a problem regarding the hitTestState of a simpleButton. Which will not take the alpha channel into account when using png's or gif's with transparancy. I found some helper classes which address the problem, but they solve the problem by repressing the eventlisteners and adding their own which check every pixel under the mouse for transparancy. This causes the cursor to flicker when entering the simpleButton the first time.
So i wrote a getHitTestShape() function wich works realy well for me and i'd like to share with u guys!
As the function name already states, it takes the image used for the button and redraws it in a shape leaving transparent pixels blank. So without further ado, here my function:

function getHitTestShapebitmapData:BitmapData):Shape
        
{
            var 
s:Shape = new Shape();
            var 
inc:int 1;
            var 
xpos:int inc 2;
            var 
ypos:int inc 2;

            var 
pxl:uint;
            var 
alphaValue:uint;
            
s.graphics.beginFill(0);
            
            while ( 
ypos bitmapData.height )
            {
                while ( 
xpos bitmapData.width )
                {
                    
pxl bitmapData.getPixel32(xpos,ypos);
                    
alphaValue pxl >> 24 0xFF;
                    if ( 
alphaValue != )
                    {
                        
s.graphics.drawRect(xpos - (inc 2), ypos - (inc 2), incinc);
                    }
                    
xpos +=  inc;
                }
                
xpos inc 2;
                
ypos +=  inc;
            }
            
s.graphics.endFill();
            return 
s;
        } 


Used on a simpleButton :

var testBTN:SimpleButton = new SimpleButton();
var 
logo:Bitmap = new Bitmap(new abLogo(0,0));

// in this case abLogo is a png out of the libary

testBTN.upState logo; 

testBTN.downState logo; 
testBTN.overState logo;
testBTN.hitTestState getHitTestShape(logo.bitmapData);
addChild(testBTN)

in this case i draw every pixel, u can reduce the accuracy to 
what ever is appropriate for you by changeing var inc.
but i testet it with fairly big png's and the performance was fine,
hope this helps someone, drop me a line if it does ...
enjoy