---
title: "AS3图形基础：画虚线矩形框"
author: "hacker47"
date: "2012-04-07T19:39:28Z"
tags: []
categories: ["Web前端"]
slug: "as3"
draft: false
lastmod: "2012-04-07T19:39:28Z"
id: 1478171
url: "https://hacker47.iteye.com/blog/1478171"
---

画虚线矩形框的需求常常都有，虽然API里没有提供现成的线条样式，但是实现起来并不困难。
先看图，按下鼠标拖动。

![](http://dl.iteye.com/upload/attachment/0066/1563/318021af-d759-3e7f-ae0e-cd874e1a4df1.jpg)

主要代码如下：


```java

package 
{
	import com.duowan.util.DrawUtil;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	/**
	 * ...
	 * @author hacker47
	 */
	public class Main extends Sprite 
	{
		private var p0:Point = new Point();
		private var drawWidth:Number;
		private var drawHeight:Number;
		
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
		}
		
		private function onDown(e:MouseEvent):void {
			p0.x=mouseX;
			p0.y= mouseY;
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
			stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
		}
		
		private function onMove(e:MouseEvent):void {
			var dx:Number = mouseX - p0.x;
			var dy:Number = mouseY -p0.y;
			graphics.clear();
			DrawUtil.drawRect(graphics, p0, dx, dy);
		}
		
		private function onUp(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
		}
		
		
		
	}
	
}

```




```java


public static function  drawDashed(graphics:Graphics,p1:Point,p2:Point,length:Number=5,gap:Number=5):void   
		{   
			graphics.lineStyle(1);
			var max:Number = Point.distance(p1,p2);    
			var l:Number = 0;    
			var p3:Point;    
			var p4:Point;    
			while(l<max)    
			{    
				p3 = Point.interpolate(p2,p1,l/max);    
				l+=length;    
				if(l>max)l=max    
				p4 = Point.interpolate(p2,p1,l/max);    
				graphics.moveTo(p3.x,p3.y)    
				graphics.lineTo(p4.x,p4.y)    
				l+=gap;    
			}    
		}



```