In my recent work to create a cross-platform gui abstraction, I found that Core Graphics on MacOS does not offer a convenient way to draw non-axis-aligned elliptical arcs, like the svg command. There are a number of approaches I could take to address this problem. For instance, I can use the midpoint ellipse algorithm to rasterize an ellipse onto a bitmap to render onto the screen. Given that I'm implementing a core graphics abstraction, I would have to somehow integrate all of the path stroke and fill effects, as well as anti-aliasing if that is given as an option. Moreover, if core graphics were to use the GPU for rasterization, then I would have to write the rasterizer in Metal, to achieve performance parity. But this is all getting very messy. Another option, but not one I went with, is to use the axis-aligned circle-drawing API provided by core graphics, and applying matrix transforms and clipping paths to the path to turn it into an ellipse. This offers a simple implementation, and one I may pursue in the future. However the implementation this post discusses will turn an ellipse into a series of cubic bezier curves. Cubic bezier curves are functions of order 3 that can be defined by their endpoints and two control points. Being polynomials, they cannot represent conic sections, like circles and ellipses. Note, a rational function can represent conics, which are used by some graphics implementations (see NURBS). However, one can use a sequence of higher order polynomials to approximate an ellipse. At a high level, the newly generated control points are gotten by combining the arc's parametric equation and derivative evaluated at the endpoints, as well as the solution to a system of equations evaluated using the angle from the arc to the center of the ellipse. A detailed derivation of the algorithm is given by Maisonobe in this paper. In order to implement the SVG elliptical arc api, one needs to convert from endpoint parameterization to center parameterization. The endpoint syntax is defined by
NaN
s for certain arguments to sqrt
or arccos
. This blog post from Musing Monday describes the fixes applied below.