CGPath adding a curve between points

只谈情不闲聊 提交于 2019-12-06 04:34:27

问题


So I have a function which randomly generates some CGPoints I then create a CGPath from these points. I use this path in a keyframe animation to animate a view around the screen.

The path is generated using the code below:

- (CGMutablePathRef)generatePathFromCoordinates:(NSArray *)coordinates
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGPoint point = [(NSValue *)[coordinates objectAtIndex:0] CGPointValue];
    CGPathMoveToPoint(path, nil, point.x, point.y);

    for (int i=1; i < coordinates.count; i++)
    {
        point = [(NSValue *)[coordinates objectAtIndex:i] CGPointValue];
        CGPathAddLineToPoint(path, nil, point.x, point.y);
    }

    return path;   
}

The above code works great but the animation looks a little strange, so I'd like to add a curve between coordinates rather than a straight line. Like the picture below (amazing paint skills i know!). Path 'A' is what I'm currently doing and path 'B' is what I'm aiming for:

After having a look at the functions available in the CGPath reference I can see a few which might get the job done, CGPathAddArcToPoint CGPathAddCurveToPoint. I've had a brief go at using these functions but wasn't able to get the desired effect (probably because I was using them incorrectly)

Could you guys point me in the right direction to achieve a nice curve?

Thanks in advance


回答1:


CGPathAddCurveToPoint adds a cubic curve to the bezier path. In the case you don't know it, it's made in a way that the shape of the curve is determined by two control points (uses a third grade equation for the curve). If you want the curve to have a particular shape, then you need to calculate two intermediate points, biased on the value of the path current point, and the curve end point. If instead you don't care about having a curve with a particular shape, you can just pick some random points. This is an implementation example:

for (int i=1; i < coordinates.count; i++)
{
    point = [[coordinates objectAtIndex:i] CGPointValue];
    CGPathAddCurveToPoint(path, 0, randomX(), randomY(), randomX(), randomY(), point.x, point.y);
}

I see the you used CGPath, but you can also use OOP with UIBezierPath instead of CGPath, if you find it easier to use.



来源:https://stackoverflow.com/questions/17176230/cgpath-adding-a-curve-between-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!