So I have a arbitary line (See an example shown in fig 1) made up of n points
I want to draw an outline around this line (see fig 2) so I need to calculate the points of the surrounding polygon.
I started by performing a dilation on the line but this wont work - see figure 3
Any suggestions on how to do this?
I suspect calculating the normal of each line segment for use in translating the new line below and a new line above its current position and then extending each new line to infinity and defining the points as the intersections?
Create all the lines before you render them.
When you do, they should overlap, like this:
The ones I drew, obviously, are the ones that get trimmed which would reveal the outline.
First duplicate each line twice, once on each side at a distance of half the width you want from each original line. That gives you the green lines in the image. Then you need to visit them in order (numbered) and deal with the loose ends.
When the lines don't meet (2-3, 6-7 and 12-13) you add a line join (in blue). A line join can be a bevel join (2-3) by just connecting the points, or a miter join by extending the lines until they meet (6-7) or a round join by making a curve.
When the lines do meet, just take the intersection point (blue dots).
At the line ends, you need to add an end cap (also in blue). An end cap can be a butt cap (8-9) by connecting the points, a projecting cap (1-16) by extending the lines a little before connecting them, or a round cap (not shown).
The end result is a polygon (or path if it includes round joins) that you can then stroke or fill.
If you have the points of the line segments, you can easily create two parallel lines to each segment and calculate the connection point where they intersect with the next if they were lines (and not line segments). This site should give you all you need to calculate super fast intersections:
http://www.math.niu.edu/~rusin/known-math/95/line_segs
I have figured out a way to calculate the outline points of a line. For each point of the original line you will have to compute 2 points for the outline:
The colors above correspond to this image.
I have programmed this function in C, but I used Accelerate Framework so it's not very easy to read. You can find the source code here and a video running the demo here.
Here is some code of mine in Objective-C that's doing it (even if it's sometimes buggy, I don't know why, let me know how it goes for you...) :
finally it adds each point in the desired order to make a polygon
Here is some explanation for the intersection point, with C code : http://alienryderflex.com/intersect/