문제

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:

enter image description here

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top