【问题标题】:Why should I need backgoundColor when I draw lines on UIVew?为什么我在 UIView 上画线时需要背景颜色?
【发布时间】: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


    【解决方案1】:

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

    克劳斯

    【讨论】:

    • 谢谢@Claus,你的猜测也是我的猜测,所以我不能接受你的回答,但我只是对你的回答投了赞成票。
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多