【发布时间】:2014-09-26 09:53:25
【问题描述】:
我有一些如下代码:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
[self drawWithBezierPath];
//[self drawOnCurrentGraphicsContext];
}
- (void)drawWithBezierPath
{
if (self.selectedButtons.count > 0) {
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
for (int i = 0; i < self.selectedButtons.count; i++) {
if (i == 0) {
UIButton *firstButton = [self.selectedButtons objectAtIndex:0];
[bezierPath moveToPoint:firstButton.center];
} else {
UIButton *button = [self.selectedButtons objectAtIndex:i];
[bezierPath addLineToPoint:button.center];
[bezierPath moveToPoint:button.center];
}
}
[bezierPath addLineToPoint:self.currentPoint];
[bezierPath setLineWidth:5.0f];
[bezierPath setLineJoinStyle:kCGLineJoinRound];
[[UIColor yellowColor] setStroke];
[bezierPath stroke];
}
}
我想在手指移动时画线:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[self onTouch:touch];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[self onTouch:touch];
}
- (void)onTouch:(UITouch *)touch
{
if (touch) {
CGPoint point = [touch locationInView:self];
self.currentPoint = point;
UIButton *button = [self buttonContainsPoint:point];
if (button && ![self.selectedButtons containsObject:button]) {
[self.selectedButtons addObject:button];
button.selected = YES;
}
[self setNeedsDisplay];
}
}
如上图所示,当我移动手指时,它会画出许多我没想到的线条。
我知道我可以执行CGContextClearRect 之类的操作来清除之前绘制的线条,但我发现的关键是,如果没有CGContextClearRect,如果我写self.backgroundColor = [UIColor clearColor];,那么之前绘制的线条将被自动清除。
所以,如果我不显式设置背景,backgroundColor 会是nil,iOS 不会清除之前绘制的线条,或者会清除但我不知道。
谁能告诉我为什么?谢谢:-)
【问题讨论】:
标签: ios objective-c core-graphics draw quartz-2d