当我尝试在上下文中绘制UIBezierpath时,为什么会得到`CGPathGetCurrentPoint:no current point`?

时间:2016-09-08 14:00:00

标签: ios objective-c xcode uibezierpath bezier

我正在尝试使用这个方法在上下文中绘制我的bezier路径,该方法使用一个充满CGPoints的数组来绘制横跨它们的平滑路径,并且我使用NSLog来确保数组不是NULL并且它不是但是我一直收到这样的错误:CGPathGetCurrentPoint: no current point. 它并没有在我的UIView上画任何东西。我该怎么办?提前谢谢。

-(void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawBezier:rect inContext:context];  
}

- (void)drawBezier:(CGRect)rect inContext:(CGContextRef)context {
    UIBezierPath *path = [UIBezierPath bezierPath];

    //< Start and End Point
    if (self.pointCount < 2)
    {
        return;
    }

    CGPoint startPt = [[self.pointsArray objectAtIndex:0] CGPointValue];
    CGPoint endPt = [[self.pointsArray objectAtIndex:(self.pointCount - 1)] CGPointValue];

    float amount = endPt.x - startPt.x;

    int (^factorial)(int k) = ^(int k) {
        if (k == 0)
        {
            return 1;
        }
        int m = 1;
        for (int i = 1; i <= k; i++)
        {
            m *= i;
        }
        return m;
    };


    //< Curve Equation
    float (^bezierSpline)(int rank, float ux) = ^(int rank, float ux) {

        float p = 0.0f;

        for (int i = 0; i < rank; i++)
        {
            CGPoint pt = [[self.pointsArray objectAtIndex:i] CGPointValue];

            p += pt.y * powf((1 - ux), (rank - i - 1)) * powf(ux, i) * (factorial(rank - 1) / (factorial(i) * factorial(rank - i - 1)));
        }

        return p;
    };
    [path moveToPoint:startPt];

    for (float curX = startPt.x; (curX - endPt.x) < 1e-5; curX += 1.0f)
    {
        float u = (curX - startPt.x) / amount;
        [path addLineToPoint:CGPointMake(curX, bezierSpline(self.pointCount, u))];
    }

    CGContextSetLineWidth(context, 1.0f);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextAddPath(context, path.CGPath);
    CGContextStrokePath(context);
}

2 个答案:

答案 0 :(得分:0)

实现触摸开始方法,例如,

  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
[_path moveToPoint:[mytouch locationInView:self]];  // self is view here. you can pass  relevant view


 }

_pathUIBezierPath的实例变量。不要把它当作本地人!

答案 1 :(得分:0)

听起来,当路径尚未开始时,您正在呼叫CGPathGetCurrentPoint(或称呼本身称为CGPathGetCurrentPoint的内容)。例如,如果您在致电addLineToPoint之前致电moveToPoint,则会收到该错误,但我没有看到此代码执行此操作。

我建议您添加一些断点和/或日志语句,以确定导致此错误的行。我无法根据提供的代码重现您报告的错误。

不相关,我建议完全退出CGContext个功能,例如:替换线:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetLineWidth(context, 1.0f);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextAddPath(context, path.CGPath);
CGContextStrokePath(context);

使用:

path.lineWidth = 1;
[[UIColor whiteColor] setStroke];
[path stroke];