ios - 为什么在UIView上画线需要背景色?

标签 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 将不会清除之前绘制的线条,或者它会清除但我不知道。

谁能告诉我为什么?谢谢:-)

最佳答案

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

子句

关于ios - 为什么在UIView上画线需要背景色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056787/

相关文章:

ios - 如何在 Objective-C 中的 UITextField 中每次更改后调用操作?

iphone - Core Graphics 绘制形状和文本混合

ios - 从 XIB 加载 UITabBarController 不包含来自 XIB 的任何内容

ios - 如何在 Coredata 中的相同实体之间创建多个关系?

objective-c - 将filteredArrayUsingPredicate应用于多维NSMutableArray的特定列

iphone - 核心数据 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'

iphone - 如何向 UIImage 或 UIImageView 或 UIView 添加外部发光

swift - CIAdditionCompositing 段错误

ios - 当我尝试删除 UITableView 部分时 EXC_BAD_ACCESS

ios - 如何暂停自己应用程序中来自另一个应用程序的音乐?