July 08, 2009

Hightlight the selection of Sprite in Flex

Hi,
In Sprite highlighted by using the graphics for change the color selection. The getBounds() function was used to get the boundary area of the sprite based on that we can draw the graphics again with different selection color. After complete the graphics draw then placed the sprite by its position of x and y. Whenever need to change the color selection we must need redraw the sprite using the graphics. In the folowing example very nice one for selecting or highlighted the sprite based on mouse down event.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;

private var _spr:Sprite;
private var _curSpr:Sprite;
private var _prevSpr:Sprite;

private function onInit():void
{
var ui:UIComponent = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
_spr.addEventListener(MouseEvent.MOUSE_DOWN,onSelect);
_spr.x = 20;
_spr.y = 30;
ui.addChild(_spr);

_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
_spr.addEventListener(MouseEvent.MOUSE_DOWN,onSelect);
ui.addChild(_spr);
_spr.x = 230;
_spr.y = 25;

addChild(ui);
}

private function onSelect(evt:MouseEvent):void
{
_prevSpr = _curSpr;
if(_prevSpr != null)
setSelect(_prevSpr,0xFF0000);
_curSpr = evt.target as Sprite;
setSelect(_curSpr,0x00FF00);
}

private function setSelect(spr:Sprite,color:uint):void
{
var rect:Rectangle = spr.getBounds(spr.parent);

spr.graphics.clear();
spr.graphics.beginFill(color);
spr.graphics.drawRect(0,0,rect.width,rect.height);
spr.graphics.endFill();

spr.x = rect.x;
spr.y = rect.y;
}

]]>
</mx:Script>
</mx:Application>

No comments:

Post a Comment