Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant Change UIView Background Color From Black

This is my first time in which I've encountered problems with drawRect. I have a simple UIView subclass with a path to fill. Everything is fine. The path gets filled properly, but the background remains black no matter what. What should I do? My code is listed below:

var color: UIColor = UIColor.red {didSet{setNeedsDisplay()}}

private var spaceshipBezierPath: UIBezierPath{
    let path = UIBezierPath()
    let roomFromTop: CGFloat = 10
    let roomFromCenter: CGFloat = 7
    path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.midX-roomFromCenter, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.midX-roomFromCenter, y: bounds.minY))
    path.addLine(to: CGPoint(x: bounds.midX+roomFromCenter, y: bounds.minY))
    path.addLine(to: CGPoint(x: bounds.midX+roomFromCenter, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    return path
}

override func draw(_ rect: CGRect) {
    color.setFill()
    spaceshipBezierPath.fill()
}

Here is what the view looks like: enter image description here

like image 645
Nikhil Sridhar Avatar asked Jan 15 '17 20:01

Nikhil Sridhar


2 Answers

I have a simple UIView subclass ... but the background remains black no matter what

Typically that sort of thing is because you have forgotten to set the UIView subclass's isOpaque to false. It is a good idea to do this in the UIView subclass's initializer in order for it to be early enough.

For example, here I've adapted your code very slightly. This is the complete code I'm using:

class MyView : UIView {
    private var spaceshipBezierPath: UIBezierPath{
        let path = UIBezierPath()
        // ... identical to your code
        return path
    }
    override func draw(_ rect: CGRect) {
        UIColor.red.setFill()
        spaceshipBezierPath.fill()
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()        
        let v = MyView(frame:CGRect(x: 100, y: 100, width: 200, height: 200))
        self.view.addSubview(v)
    }
}

Notice the black background:

enter image description here

Now I add these lines to MyView:

override init(frame:CGRect) {
    super.init(frame:frame)
    self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

See the difference that makes?

enter image description here

like image 98
matt Avatar answered Nov 14 '22 05:11

matt


In my case what I solved was to switch from Background-Color "No Color", to Background-Color "Clear Color"

like image 1
Andreas Avatar answered Nov 14 '22 03:11

Andreas