这节课来简单介绍显示对象的几个基本属性,ButtonMode,DropTarget,hitArea以及ScaleX,ScaleY,ScrollRect。首先,介绍一下显示对象的继承关系Sprite DisplayObjectContainer InteractiveObject DisplayObject EventDispatcher Object。以上从左至右依次为子类父类继承关系,因此可知,Sprite显示对象既可作为事件分发器,也可以作为显示对象容器,还可以相应各种交互事件。以下先介绍基本属性ButtonMode,DropTarget,hitArea。
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class InteracObj extends Sprite
{
private var _circle1:Sprite = new Sprite();
private var _circle2:Sprite = new Sprite();
public function InteracObj()
{
//绘制两个圆
draw(_circle1, 0xFFCC00, 150, 40, 40);
draw(_circle2, 0xCCFF00, 150, 40, 10);
//设定圆的属性,将_circle2设为_circle1的hitArea属性。同时_circle1的buttonMode属性为true。
_circle1.hitArea = _circle2;
_circle1.alpha = 0.5;
_circle1.buttonMode = true;
_circle1.useHandCursor = true;
_circle2.mouseEnabled = false;
//将显示对象添加到舞台
addChild(_circle1);
addChild(_circle2);
//对_circle1添加侦听
_circle1.addEventListener(MouseEvent.MOUSE_DOWN, mousedownh);
_circle1.addEventListener(MouseEvent.MOUSE_UP, mouseuph);
_circle1.addEventListener(MouseEvent.CLICK, onClick);
}
private function draw(obj:Sprite, color:int, x:int, y:int, radius:int):void
{
obj.graphics.beginFill(color);
obj.graphics.drawCircle(x, y, radius);
obj.graphics.endFill();
}
private function mousedownh(event:MouseEvent):void{
_circle1.graphics.clear();
draw(_circle1, 0xCCFF00, 40, 40, 40);
_circle2.startDrag();
}
private function mouseuph(event:MouseEvent):void
{
_circle1.graphics.clear();
draw(_circle1, 0xFFCC00, 40, 40, 40);
_circle2.stopDrag();
}
private function onClick(event:MouseEvent):void
{
_circle1.scaleX *= 1.10;
}
}
}
运行结果如图所示,可以看到,此时_circle1相应鼠标事件,但是其相应鼠标事件的区域为_circle2,即使_circle2已经移出了_circle1,不在_circle1的上面。同时,ScaleX属性可以控制图形的缩放。由于gif图片录制软件的影响,看不到ButtonMode属性的效果,读者可自行编译运行看看实际效果。
以下程序研究了显示对象的ScrollRect属性,可以看见显示对象在一个矩形区域内部,当鼠标点击的时候,其不断往下移动,直至移除矩形区域。
package
{
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.events.MouseEvent;
public class InteracObj extends Sprite
{
public function InteracObj()
{
var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFFCC00);
circle.graphics.drawCircle(200, 200, 200);
circle.scrollRect = new Rectangle(0, 0, 200, 200);
addChild(circle);
circle.addEventListener(MouseEvent.CLICK, clicked);
function clicked(event:MouseEvent):void {
var rect:Rectangle = event.target.scrollRect;
rect.y -= 5;
event.target.scrollRect = rect;
}
}
}
}