Drawing dashed lines with ActionScript 3

Drawing in Flash dynamically with ActionScript is a jolly fun time, but when doing so one of course lacks some of the finer controls of drawing the graphics manually in the Flash authoring environment. One such deficiency is dashed lines, so a while back I made a simple DashedLine class in AS3 to use here and there in my projects.

It’s basically a Sprite that has simple drawing methods with dashed lines. Just make a new instance, providing the line width, color, and an array of alternating dash and gap lengths (in pixels). Then call moveTo() and lineTo() methods directly on the Sprite, not its graphics property. (You can also do beginFill() if you want.) For example:

Dashed line triangle

var dashy:DashedLine = new DashedLine(1,0x339933,new Array(8,4,2,4));
dashy.moveTo(0,50);
dashy.lineTo(100,0);
dashy.lineTo(200,50);
dashy.lineTo(300,0);
addChild(dashy);

Try it out below!

This is by no means complete, as I'd like to add the rest of the usual drawing methods (curves are going to be tricky) and resolve the bugs that surely exist.  For now, though, download the DashedLine class as is; hopefully it'll make sense through the basic comments I've included.

DashedLine.as
dashTest.zip (AS file plus the above demo FLA)

Tagged ,

52 Comments

  1. I need to draw a rectangle with this class but I can’t

    Wahid Anwer
    29 October 2013 @ 4:43pm

  2. can Anyone give me the example for creating the rectangle with this class ?

    Wahid Anwer
    29 October 2013 @ 4:45pm