Actionscript 3 Dashed Line

Friday, 15 June 2007 | Labels: , | |

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);
}
}

11 comments:

  1. Olivier Allouch says:

    Thx a lot for your simple code.
    I didn't need the whole senocular hammer.

  2. Empy says:

    Thank you very much! Simple and it works.

  3. nickdean says:

    IOYAB (I owe you a beer).

    Thanks for the solution.

  4. Rohit Sharma says:

    Thanks a lot for your code.It saved me a lot of time.

  5. Glenn says:

    Brillant! Thanks for sharing such a straight forward, easy to use routine!

  6. Anonymous says:

    Could you please add the calling code as to how we can make this to use
    Thanks

  7. Anonymous says:

    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);

    ...

  8. Anonymous says:

    When you call this, what should the first param "g' be?

  9. melodave says:

    Thanks a lot! Beauty solution.



    ...excellent :)

  10. MAvdi says:

    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();

  11. Samuel says:

    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