views:

116

answers:

1

I'm making a line graph on the iphone using core graphics and instead of having a jagged chart, I want to smooth it out like in good old math class. What's the formula to pick where to put the control points for CGContextAddCurveToPoint?

            CGFloat cp2x = (x + x + prevX);
        CGFloat cp1y = (prevY + prevY + y);

        CGFloat cp1x = (prevX + prevX + x);
        CGFloat cp2y = (y + y + prevY);

        CGContextAddCurveToPoint(context, cp1x, cp1y, cp2x, cp2y, x, y);

This code almost works but doesn't take into account 3 points.

A: 

I ended up doing something like this that worked well:

CGPoint prevItemPosition2 = [self positionForItem: prevItem2 andMaxItem:maxItem inItems: items];
CGPoint prevItemPosition1 = [self positionForItem: prevItem1 andMaxItem:maxItem inItems: items];
CGFloat cpAngle = atan2f((prevItemPosition2.y - prevItemPosition1.y),
                          (prevItemPosition2.x - prevItemPosition1.x));
cpAngle += M_PI;
CGFloat magnitude = sqrtf(powf(prevItemPosition1.x - itemPosition.x, 2) + 
                          powf(prevItemPosition1.y - itemPosition.y, 2)) / 3;
CGPoint angleComponents = CGPointMake(cos(cpAngle) * magnitude, 
                                      sin(cpAngle) * magnitude);
CGPoint cp = CGPointMake(prevItemPosition1.x + angleComponents.x, 
                          prevItemPosition1.y + angleComponents.y);
CGContextAddQuadCurveToPoint(context, cp.x, cp.y, itemPosition.x, itemPosition.y);
Matt Williamson