<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="700" height="450" applicationComplete="applicationCompleteHandler(event)" backgroundColor="0xFFFFFF" backgroundGradientColors="[0xFFFFFF,0xFFFFFF]" fontSize="12" layout="absolute" viewSourceURL="http://img.l4cd.net/attachment/snap-to-grid/srcview/" > <mx:Script> <![CDATA[ import mx.events.FlexEvent; protected var hGap:Number; protected var vGap:Number; protected function clickHandler(event:MouseEvent):void { hGap = h.value * 10; vGap = v.value * 10; drawGrid(); } private function drawGrid():void { content.graphics.clear(); content.graphics.lineStyle(2,0xFF0000); var pos:Number = 0; while(pos < content.width) { pos += vGap; content.graphics.moveTo(pos,0); content.graphics.lineTo(pos,content.height); } pos = 0; while(pos < content.height) { pos += hGap; content.graphics.moveTo(0,pos); content.graphics.lineTo(content.width,pos); } } protected function applicationCompleteHandler(event:FlexEvent):void { clickHandler(null); dot = new Sprite(); dot.graphics.beginFill(0xFF6600,0.75); dot.graphics.drawCircle(0,0,10); dot.graphics.endFill(); content.addChild(dot); dot.x = dot.y = 40; dot.addEventListener(MouseEvent.MOUSE_DOWN,onSpriteDown); } protected var dot:Sprite; protected function onSpriteDown(event:MouseEvent):void { stage.addEventListener(MouseEvent.MOUSE_MOVE,onDragMove); stage.addEventListener(MouseEvent.MOUSE_UP,onDragStop); onDragMove(event); } protected function onDragMove(event:MouseEvent):void { var targetX:int = event.stageX; var targetY:int = event.stageY; var distanceX:Number = 0; var distanceY:Number = 0; if(snap.selected) { distanceX = 10; distanceY = 10; } if(lock.selected) { distanceX = hGap / 2; distanceY = vGap / 2; } //最主要代码,判断当前位置是否在网格的上下左右指定像素内 var value:int; if(distanceX > 0) { value = targetX % hGap; if(value < distanceX) { targetX -= value; }else if(value >= hGap - distanceX) { targetX += hGap - value; } } if(distanceY) { value = targetY % vGap; if(value < distanceY) { targetY -= value; }else if(value >= vGap - distanceY) { targetY += vGap - value; } } dot.x = targetX; dot.y = targetY; event.updateAfterEvent(); } protected function onDragStop(event:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_MOVE,onDragMove); stage.removeEventListener(MouseEvent.MOUSE_UP,onDragStop); } ]]> </mx:Script> <mx:UIComponent id="content" left="0" right="0" top="0" bottom="0"> </mx:UIComponent> <mx:NumericStepper id="h" x="10" y="418" maximum="10" minimum="1" value="4"/> <mx:NumericStepper id="v" x="75" y="418" maximum="10" minimum="1" value="4"/> <mx:Button x="140" y="418" label="生成网格" click="clickHandler(event)"/> <mx:CheckBox id="snap" x="222" y="418" label="Snap To Grid" selected="true"/> <mx:CheckBox id="lock" x="333" y="418" label="Lock To Grid"/> </mx:Application>?