我有一些代码如下:
- (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 - 为什么在UIView上画线需要背景色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056787/