Tuesday, 14 February 2012

Quadratic curve through three points

Flash has a couple of curve drawing functions in the Graphics class, curveTo and cubicCurveTo, but they can be difficult to use as they use control points. Control points are points off the curve which the curve tends towards. They are intuitive to use when editing in a graphics app but less useful in code when a curve through a point is needed.

Fortunately it's straightforward to draw a quadratic curve through three points using curveTo. curveTo uses three points to draw its curve: the start point (the last point drawing was done), the end point and the control point off the curve. The curve goes from the start point to the end point, missing the control point but passing through a point half way between the control point and the midpoint of the line.

This means, given this point on the curve (which is treated as the curve's midpoint but it need not be, the control point can be calculated, as

Pcontrol = Pcurvemid + (Pcurvemid - Plinemid) = 2 * PcurvemidPlinemid

Where the points are treated as vectors. If the curve is symmetric about one of the axes then the control point is above/to the side of the curve midpoint and only its height or distance needs to be calculated.

To demonstrate this I've updated my Ballistics app, also embedded below, replacing hundreds of drawRect calls in a loop with a single call to curveTo in the function DrawCoverage. As the curve is symmetric and upright only the height needs to be calculated, as fMidY + fMidY - fLeftY in the code.

No comments:

Post a comment