1 package { 2 import flash.display.Sprite; 3 import flash.events.Event; 4 import flash.geom.Matrix; 5 import flash.geom.Point; 6 7 public class LoadMotion extends Sprite { 8 public static const STYLE_RECT:int = 0; 9 public static const STYLE_CIRCLE:int = 1; 10 public static const STYLE_SQUARE:int = 2; 11 private var _defaultStyle:int = 1; 12 private var _color:uint = 0; 13 private var _itemNum:int = 9; 14 private var _refreshFrame:int = 1; 15 private var _box:Sprite; 16 17 public function get refreshFrame():int { 18 return _refreshFrame; 19 } 20 private var degree:Number; 21 22 /** 23 * 刷新间隔的帧数 24 * @param value 25 * 26 */ 27 public function set refreshFrame(value:int):void { 28 if (value < 1) { 29 _refreshFrame = 1; 30 } else { 31 _refreshFrame = value; 32 } 33 } 34 /** 35 * 转动速度 36 */ 37 public var rotateSpeed:int = 1; 38 private var _dir:int = 1; 39 40 /** 41 * 42 * @param color 43 * @param radius 每个子块到中心的距离 44 * @param maxNum 子块数目 45 * @param style 子块样式 46 * @param dir 转动方向 47 * 48 */ 49 public function LoadMotion(color:int = 0xffffff, radius:int = 50, itemNum:int = 9, style:int = STYLE_CIRCLE, dir:int = 1) { 50 _color = color; 51 _itemNum = itemNum; 52 _defaultStyle = style; 53 _dir = dir; 54 _box = new Sprite(); 55 degree = 360 / _itemNum; 56 _refreshFrame = Math.ceil(degree / 5); 57 var factor:Number = 1 / itemNum; 58 59 for (var i:int = 0; i < _itemNum; i++) { 60 var item:Sprite = buildItem(); 61 item.rotation = i * degree * _dir; 62 var pt:Point = new Point(radius); 63 pt = rotatePoint(item.rotation * Math.PI / 180, pt); 64 item.x = pt.x; 65 item.y = pt.y; 66 var v:Number = factor * i; 67 item.alpha = v; 68 item.scaleX = item.scaleY = v; 69 _box.addChild(item); 70 } 71 72 _box.cacheAsBitmap = true; 73 addChild(_box); 74 } 75 76 private function rotatePoint(radian: Number, pt: Point, center: Point = null):Point { 77 if (center == null) { 78 center = new Point(); 79 } 80 var matrix:Matrix = new Matrix(1, 0, 0, 1, pt.x - center.x, pt.y - center.y); 81 matrix.rotate(radian); 82 return new Point(matrix.tx + center.x, matrix.ty + center.y); 83 } 84 85 public function start():void { 86 addEventListener(Event.ENTER_FRAME, onEnterFrameHandler); 87 } 88 89 public function stop():void { 90 removeEventListener(Event.ENTER_FRAME, onEnterFrameHandler); 91 } 92 93 private var _counter:int = 0; 94 95 private function onEnterFrameHandler(e: Event):void { 96 if (_counter % refreshFrame == 0) { 97 _box.rotation += _dir * degree * rotateSpeed; 98 _counter = 0; 99 } 100 _counter += 1; 101 } 102 103 private function buildItem():Sprite { 104 var item:Sprite = new Sprite(); 105 item.graphics.beginFill(_color); 106 if (_defaultStyle == STYLE_CIRCLE) { 107 item.graphics.drawCircle(-5, -5, 10); 108 } else if (_defaultStyle == STYLE_RECT) { 109 item.graphics.drawRect(-10, -5, 20, 10) 110 } else if (_defaultStyle == STYLE_SQUARE) { 111 item.graphics.drawRect(-10, -10, 20, 20) 112 } 113 item.graphics.endFill(); 114 return item; 115 } 116 } 117 }