Friday, March 23, 2007

Creating a new hit-area for a button in Flex Builder 2.0.1

I ran into this yesterday, and thought I'd put it up here & share with the class.

I have a button in mxml:

<mx:button x="-22" y="294" id="reallyBigButton" stylename="reallyBigButtonStyle" buttonmode="true" usehandcursor="true" creationcomplete="addHitArea()" />
It's really big, this button, and I only want a portion of it to be the hit area. The button is skinned via css with a .png file, and it covers about a sixth of the pixellated real-estate. Not good.

So notice that on creationcomplete it calls a function addHitArea().

That function looks like this:

private function addHitArea():void{
var newHitArea:Sprite = new Sprite();
newHitArea.visible = false;
newHitArea.mouseEnabled=false;
newHitArea.graphics.clear();
newHitArea.graphics.beginFill(0x000000, 1.0);
newHitArea.graphics.drawCircle(117,216,80);
newHitArea.graphics.endFill();
reallyBigButton.addChild(newHitArea);
reallyBigButton.hitArea = newHitArea;
reallyBigButton.validateDisplayList();
}
Notice a couple of things: the new hit area doesn't need to be visible. And it should have mouseEnabled set to false. You want the button to reference the button sprite for size and location, but not to capture control of any click events. Click events are still captured by the button.

Why the graphics.clear? I'm not sure, other than good-practice. Clean the board before scribbling, I suppose.

Keep in mind that the coordinates of the hitarea sprite are relative to the coordinates of the button, not of the stage or the button's parent.

2 comments:

  1. I ran into the same problem couple of days ago. I had to use PNG images with transparency regions for my buttons. Problem is that Flex ignores the transparent part completley and takes it as a hitarea. Since I was to lazy to draw a custom hitarea with a sprite for every button I wrote a "png to sprite" function that does the job automatically.

    ReplyDelete
  2. I haven't tried it, but I saw that there is a property called mouseEnabledWhereTransparent that should be able to do that.

    ReplyDelete