Fork me on GitHub

Maschinenbordbuch

Dashed Lines For AS3


Demo – Click to draw.

For a recent project I was looking into solutions to draw a dashed line with Flash in AS3.
Most 2D canvas implementations include such a line style, not so flash. I stumbled upon many
diverting solutions, where some where implemented using bitmap tiles to draw the line parts,
which is awfull. Luckily one of the first search results brought me to the DashedLine class by Andy Woodruff.
A very neat solution which also resolves correctly drawn corners.

Unfortunately the class was too unflexible for my purpose and like many other solutions it is heavy weight by being a complete sprite decendant, including two shapes for drawing. So I refactored it to be more of a drawing helper.
I also removed most of the comments, because the code speaks for itself and good code does not need inline comments.
But that’s another topic.

Anyway, here is an example of its usage:

1
2
3
4
5
6
var canvas:Shape = new Shape();
canvas.graphics.lineStyle(2, 0x334455);
DashedLine.moveTo(canvas.graphics, -50, 50);
DashedLine.lineTo(canvas.graphics, 50, 50);
DashedLine.lineTo(canvas.graphics, 0, -50);
DashedLine.lineTo(canvas.graphics, -50, 50);

This actually draws a little triangle with default line settings. The parameter for the line style is the same
as in the original, except that it is set by DashedLine.setDashes() which takes an Array specifying the dash/gap lengths
in the infinite format [dash,gap,...,dash,gap]. Play with the dash format textfield in the demo.

I moved the class to my public as3components repository, which also includes the demo
and is availible at http://www.github.com/kommander/as3components

Be Sociable, Share!

2 Comments

    Thought I’d celebrate the one-year anniversary of this post by saying thanks for a really valiant effort – but unfortunately the ‘while’ loop consistently crashes the player, particularly in situations where the line drawing is controlled by the user’s mouse. If the mouse is moved and clicked quickly, the loop times out and the player crashes. Otherwise a great class.

  • Great post.

    I am trying to use this to create the dashed line when mouse down and then finish line on mouse up. I can get it to work but the line itself doesn’t show while pressed so it only becomes visible on mouse up. Any thoughts?

Leave a Reply