Wednesday, April 14, 2010

IPhone: Graph drawing?

My favorite playthings are drawing on screen and optimizations. So I was the one who did the graph drawing research for the iPhone project.There are several graphing components on the internet available, but all are more generalized than we need.
We don't have GraphKit available on the iPhone, so I think it is the best to work with our own component. It took two days to write the code for it, it's easily used, and it has all the features we need.
As far as I know, there is no curve drawing trough arbitrary points on the iPhone, so one must write his own algorithm for this.

Calculating all points for the curve isn't a good idea, because it consumes lots of processor power, so I've chosen to create segments of lines - more segments, the curve is smoother.
Ok, segments, but how to get new point on the curve to draw these segments?
And here comes the math part - Lagrange Polynomial (you will love this):where N is the number of points we already have.
It's not the best interpolation (best would be natural cubic spline) - we have the start and end points fixed, otherwise the curve ends would fly off fast from the screen with this formula

The drawing itself is based on Quartz2D. If you have the right math formula, the rest is easy. Rock on!

1 comment:

  1. I've been looking for something to smooth out the curves created by a list of points captured by the touchesMoved method on iPhone.

    I'm not good at math! Do you know of any "code" functions that will do what you have described here?? Or do you know where I can find some?

    I would like to smooth the curve of the users drawing. I figure I will hold the points in an array while drawing the liner line. Then when the user is done drawing, take the list of points and apply the spline interpolation to them and redraw it, replacing the original liner line drawing. I like the idea of adding points in between to create a smoother look.

    Any ideas or suggestions?