Actionscript 3 Dashed Line
Friday, 15 June 2007 | Labels: Actionscript, Graphics | |Some code to draw dashed lines.
public static function dashLine(g:Graphics,x1:Number,y1:Number,x2:Number,y2:Number,onLength:Number = 0,offLength:Number = 0):void {
g.moveTo(x1,y1);
if (offLength==0) {
g.lineTo(x2,y2);
return;
}
var dx:Number = x2-x1,
dy:Number = y2-y1,
lineLen:Number = Math.sqrt(dx*dx + dy*dy),
angle:Number = Math.atan2(dy, dx),
cosAngle:Number = Math.cos(angle),
sinAngle:Number = Math.sin(angle),
ondx:Number = cosAngle*onLength,
ondy:Number = sinAngle*onLength,
offdx:Number = cosAngle*offLength,
offdy:Number = sinAngle*offLength,
x:Number = x1,
y:Number = y1;
var fullDashCountNumber:int = Math.floor(lineLen/(onLength+offLength));
for (var i:int=0; i<fullDashCountNumber; i++){
g.lineTo(x+=ondx,y+=ondy);
g.moveTo(x+=offdx,y+=offdy);
}
var remainder:Number = lineLen - ((onLength+offLength)*fullDashCountNumber);
if (remainder>=onLength) {
g.lineTo(x+=ondx,y+=ondy);
} else {
g.lineTo(x2,y2);
}
}
Thx a lot for your simple code.
I didn't need the whole senocular hammer.
Thank you very much! Simple and it works.
IOYAB (I owe you a beer).
Thanks for the solution.
Thanks a lot for your code.It saved me a lot of time.
Brillant! Thanks for sharing such a straight forward, easy to use routine!
Could you please add the calling code as to how we can make this to use
Thanks
Got erratic painting results until I broke out each variable. For example:
var dx:Number = x2-x1;
var dy:Number = y2-y1;
var lineLen:Number = Math.sqrt(dx*dx + dy*dy);
var angle:Number = Math.atan2(dy, dx);
...
When you call this, what should the first param "g' be?
Thanks a lot! Beauty solution.
...excellent :)
Thank you for simple and time saving solution
here is an example call to the function, you need to give a line style to your graphic object as seen below
dottedLine.graphics.clear();
dott dottedLine.graphics.lineStyle(2,0x000000,1);
LineUtils.dashLine(dottedLine.graphics, 50, 50, 200, 200,3, 10);
dottedLine.graphics.endFill();
You don't need to calculate the sine and cosine of the dx/dy values... once your normalize them, they are the sine and cosine values
dX
dY
length = Math.sqrt(dX*dX + dY*dY);
iLength = 1.0/length;
cos = dX*iLength;
sin = dY*iLength;
doing this also gets rid of your need for the atan2 function.
all in all... once you have the normalized values sin and cos, you're good to go. This is a huge speed increase if you have a LOT of lines to draw