0

我目前有以下代码来尝试允许用户绘制虚线路径并制作自定义形状。一旦他们做出这个形状,我希望它自动填充颜色。那没有发生。

目前我收到以下代码的此错误:

<Error>: CGContextClosePath: no current point.

这是我正在使用的代码:

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

UITouch *touch = [touches anyObject];

CGPoint previous = [touch previousLocationInView:self];
CGPoint current = [touch locationInView:self];

#define SQR(x) ((x)*(x))
//Check for a minimal distance to avoid silly data
if ((SQR(current.x - self.previousPoint2.x) + SQR(current.y - self.previousPoint2.y)) > SQR(10))
{

    float dashPhase = 5.0;
    float dashLengths[] = {10, 10};
    CGContextSetLineDash(context,
                         dashPhase, dashLengths, 2);

    CGContextSetFillColorWithColor(context, [[UIColor lightGrayColor] CGColor]);
    CGContextFillPath(context);

    CGContextSetLineWidth(context, 2);
    CGFloat gray[4] = {0.5f, 0.5f, 0.5f, 1.0f};
    CGContextSetStrokeColor(context, gray);

    self.brushSize = 5;
    self.brushColor = [UIColor lightGrayColor];

    self.previousPoint2 = self.previousPoint1;
    self.previousPoint1 = previous;
    self.currentPoint = current;

    // calculate mid point
    self.mid1 = [self pointBetween:self.previousPoint1 andPoint:self.previousPoint2];
    self.mid2 = [self pointBetween:self.currentPoint andPoint:self.previousPoint1];

    if(self.paths.count == 0)
    {

    UIBezierPath* newPath = [UIBezierPath bezierPath];

    CGContextBeginPath(context);

    [newPath moveToPoint:self.mid1];
    [newPath addLineToPoint:self.mid2];
    [self.paths addObject:newPath];

    CGContextClosePath(context);

    }

    else

    {

        UIBezierPath* lastPath = [self.paths lastObject];

        CGContextBeginPath(context);

        [lastPath addLineToPoint:self.mid2];
        [self.paths replaceObjectAtIndex:[self.paths indexOfObject:[self.paths lastObject]] withObject:lastPath];

        CGContextClosePath(context);

    }

    //Save
    [self.pathColors addObject:self.brushColor];

    self.needsToRedraw = YES;
  [self setNeedsDisplayInRect:[self dirtyRect]];
  //[self setNeedsDisplay];
}

}

为什么会发生这种情况,为什么路径内部没有填充颜色?

4

1 回答 1

2

您的代码有几个问题:

  • 您应该在视图的drawRect:方法中进行绘图,而不是触摸处理程序。
  • 您永远不会context使用当前上下文的值设置变量。用方法做到这一点 UIGraphicsGetCurrentContext()。再次,在你的drawRect:方法范围内。
  • 您经历了创建UIBezierPath对象的麻烦,但您从不使用它。通过调用CGContextAddPath( context, newPath.CGPath ),在您出现的两个地方根据需要更改变量名称使用UIBezierPath.
  • 将调用保留setNeedsDisplayInRect:在您的触摸处理程序方法中。这告诉系统使用您的(尚未实现的)drawRect:方法绘制的绘图来更新您的视图。
于 2012-10-23T08:35:35.620 回答