Cesare
Cesare

Reputation: 9419

Why is the background color of my drawable view black?

I would like the backgroundColor property of my UIView to be red or yellow. Though, the view displays a black color.

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);
    }
}

The line I can draw on the view is yellow, but the view is still black. Here's a sample project. Why do you think this is happening?

Upvotes: 1

Views: 229

Answers (1)

matt
matt

Reputation: 535306

It's because you're calling CGContextClearRect. The effect of this call can be quite tricky (as I explain in my online book). If you want the view's background to be red, then at the start of your drawRect: you should fill the context's bounds with red.

Upvotes: 1

Related Questions