最近发现这个算法存在潜在的隐患。由于最近才发现所以立刻就将算法修正了。
原算法并未检测在起点和终点一致的情况下该怎样画线。如果不打补丁,消除这个bug那么,将会出现死机
或内存泄漏的情况。
更改:判断,将起点和终点是否一致,若是,则直接返回。
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="white" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.containers.Canvas;
import mx.controls.Alert;
public var canvas:Canvas = new Canvas();
public function init():void
{
canvas.graphics.lineStyle(1,0);
drawLine09(0,0,500,500);
point(10,10);
addChild(canvas);
}
public function point(x:int,y:int):void
{
canvas.graphics.moveTo(x-1,y-1);
canvas.graphics.lineTo(x,y);
}
public function drawLine(xFrom:int,yFrom:int,xTo:int,yTo:int,dashStart:int,dash:int,gap:int,canvas:Canvas):void
{
var dx1:int = xTo - xFrom;
var dy1:int = yTo - yFrom;
var incX:int;
var incY:int;
if(dx1 > 0)//判断增量的符号
incX = 1;
else
incX = -1;
if(dy1 > 0)
incY = 1;
else
incY = -1;
var angle:Number = Math.atan((yFrom-yTo)/(xFrom-xTo));//求线的角度
xFrom = xFrom + dashStart*Math.abs(Math.cos(angle))*incX;
yFrom = yFrom + dashStart*Math.abs(Math.sin(angle))*incY;
var lineLength:Number = Math.sqrt( (xFrom-xTo)*(xFrom-xTo)+(yFrom-yTo)*(yFrom-yTo) );//求线的长度
var steps:uint = int(lineLength/(dash+gap))+1;
var xstart:Number =xFrom;
var xend:Number;
var ystart:Number =yFrom;
var yend:Number;//自此准备工作已经完成
for(var i:int;i<steps;i++)
{
//画实线
xend = xstart+dash*Math.abs(Math.cos(angle))*incX;
yend = ystart+dash*Math.abs(Math.sin(angle))*incY;//开始迭代
if(i == steps -1)
{
if(Math.abs(xend - xFrom) > Math.abs(xTo - xFrom)){
xend = xTo;
yend = yTo;
}
if(Math.abs(yend - yFrom) > Math.abs(yTo - yFrom)){
xend = xTo;
yend = yTo;
}
}
canvas.graphics.moveTo(xstart,ystart);
canvas.graphics.lineTo(xend,yend);//划线结束
xend = xend+gap*Math.abs(Math.cos(angle))*incX;
yend = yend+gap*Math.abs(Math.sin(angle))*incY;
xstart = xend;
ystart = yend;
}
}
public function drawLine09(xStart:Number,yStart:Number,xEnd:Number,yEnd:Number):void//使用数组
{
canvas.graphics.lineStyle(1,0);//画起点
var array:Array = [5,1,1,5];
var sum:int;
for(var i:int; i<array.length-1;i++)
{
sum = sum+array[i];//计算一个steps内所有实线部分的总长
}
var add:int;
var gap:int = array[array.length-1]; //表示非实线部分
if(array[0]!=0)
if(!((xStart == xEnd)&&(yStart == yEnd)))
for(var j:int;j<array.length - 1;j++)
{
drawLine( xStart, yStart, xEnd , yEnd, add + j*gap,array[j],(array.length-1)*gap +sum - array[j],canvas );
add += array[j];
}
point(xStart,yStart);
point(xEnd,yEnd);
}
]]>
</mx:Script>
</mx:Application>