我目前有以下代码尝试允许用户绘制虚线路径并创建自定义形状。一旦他们制作了这个形状,我希望它能自动填充颜色。那种情况没有发生。
目前我收到以下代码的错误:
<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];
}
}
为什么会发生这种情况?为什么路径内部没有填充颜色?
答案 0 :(得分:2)
您的代码存在一些问题:
drawRect:
方法中进行绘制,而不是触摸处理程序。context
设置当前上下文的值。使用UIGraphicsGetCurrentContext()
方法执行此操作。再次,在drawRect:
方法中。UIBezierPath
对象的麻烦,但您从未使用它。通过致电CGContextAddPath( context, newPath.CGPath )
,在您使用UIBezierPath
显示的两个地方根据需要更改变量名称,即可。setNeedsDisplayInRect:
的调用。这告诉系统使用您(尚未实现的)drawRect:
方法绘制的图形来更新视图。