为什么我的可绘制视图的背景颜色是黑色的?

Why is the background color of my drawable view black?

我希望 UIViewbackgroundColor 属性 是红色或黄色。但是,视图显示黑色。

class RenderView:UIView {

    var pointsToDraw:[Int] = [] {
        didSet {
            self.setNeedsDisplay()
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.backgroundColor = UIColor.whiteColor()
    }


    override func drawRect(rect: CGRect) {

        let context = UIGraphicsGetCurrentContext();
        CGContextClearRect(context, self.bounds);
        CGContextSetLineWidth(context, 3);
        UIColor.yellowColor().set()


        if pointsToDraw.count > 4 {

            CGContextMoveToPoint(context, CGFloat(pointsToDraw[0]), CGFloat(pointsToDraw[1]))

            for i in 2..<pointsToDraw.count {
                if i % 2 == 0 {
                    CGContextAddLineToPoint(context, CGFloat(pointsToDraw[i]), CGFloat(pointsToDraw[i + 1]))
                }
            }
        }

        // Draw
        CGContextStrokePath(context);
    }
}

我可以在视图上画的线是黄色的,但视图仍然是黑色的。 Here's a sample project。为什么会发生这种情况?

这是因为您正在调用 CGContextClearRect。这个调用的效果可能非常棘手(正如我解释的 in my online book)。如果您希望视图的背景为红色,那么在 drawRect: 的开头您应该用红色填充上下文的边界。