【发布时间】:2012-10-23 07:04:10
【问题描述】:
我目前有以下代码来尝试允许用户绘制虚线路径并制作自定义形状。一旦他们做出这个形状,我希望它自动填充颜色。这不会发生。
目前我收到以下代码的此错误:
<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];
}
}
为什么会发生这种情况,为什么路径内部没有填充颜色?
【问题讨论】:
-
我不是自定义绘图方面的专家,但如果我没记错的话,绘图应该(甚至必须?)发生在 drawRect: 方法中。也许这就是这里的问题?
-
但用户需要确定画线的位置,而不是应用程序 :) 所以我必须使用 touchesMoved 不是吗?
-
不,您可以将用户触摸的点保存到属性或 ivar,并在 drawRect: 方法中使用它来实际绘制到路径。
-
网上有没有这样的例子?
-
可能,但我不知道在哪里 ;) 但是您可以使用与您现在使用的基本相同的代码。只需将代码从 touchesMoved 移动到 drawRect。然后在 touchesMoved 中将当前(点)保存到一个数组中。在 drawRect 方法中,您遍历数组“解包”其中的点。
标签: iphone objective-c ios xcode cgcontext