所以我制作了一个自定义UIView,我可以根据游戏中发生的事情绘制线条,这一切似乎都正常工作(每次调用drawRect:它追加 a划到视图上)
//Initialization
DrawView* draw = [[DrawView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//And the drawRect method:
- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGColorRef r = [self.lineColor CGColor];
CGContextSetStrokeColor(c, CGColorGetComponents(r));
CGContextBeginPath(c);
CGContextMoveToPoint(c, self.start.x, self.start.y);
CGContextAddLineToPoint(c, self.finish.x, self.finish.y);
CGContextStrokePath(c);
}
然而,我注意到我忘了清除背景,以免它阻挡视图的背景。但是一旦我在初始化时设置背景颜色,drawRect方法现在每次调用drawRect时都会重置上下文。
DrawView* draw = [[DrawView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[draw setBackgroundColor: [UIColor clearColor]];
我希望每次调用drawRect时将笔划追加上下文,不清除它然后绘制,但我还需要清除视图的背景颜色。
我在这里做错了什么?
答案 0 :(得分:1)
将我的评论总结为答案:
drawRect:
必须重绘所有内容。它不是为了每次只添加一个新行而设计的。您的代码无法正常工作,因为每次都不会绘制所有行。
您需要跟踪数组中的每一行或其他适当的数据结构。然后,每次调用时,drawRect:
方法都会绘制每一行。
这将允许背景颜色按预期工作。
这也有一个优点,你可以用你的数组行做更多。您可以提供撤消/重做支持,缩放,旋转等。
另一种选择是使用UIBezierPath
而不是保留一系列行。您可以更新路径并使用drawRect:
方法进行渲染。
以下几行:
CGColorRef r = [self.lineColor CGColor];
CGContextSetStrokeColor(c, CGColorGetComponents(r));
可以替换为:
[self.lineColor setStroke];