当我在UIView上画线时,为什么需要背景颜色?

时间:2014-09-26 09:53:25

标签: ios objective-c core-graphics draw quartz-2d

我有一些代码如下:

- (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];
    }
}

enter image description here

如上图所示,当我移动手指时,它会画出许多我不想要的线条。

我知道我可以做CGContextClearRect之类的事情来清除以前绘制的线条,但我发现的关键是,如果我没有CGContextClearRect,如果我写self.backgroundColor = [UIColor clearColor];,那么绘制的线条之前将自动清除。

enter image description here

所以,如果我没有明确地设置背景,那么backgroundColor将是nil,并且iOS不会清除之前绘制的线条,或者它确实如此,但我不知道。

有人可以告诉我为什么吗?谢谢: - )

1 个答案:

答案 0 :(得分:1)

我猜,更改背景颜色会清除您的图纸。因此,您可以使用您想要的任何颜色。如果您将背景颜色设置为红色,则所有内容都将为红色,您的线条也将被清除。

克劳斯