Drawing a rectangle in UIView

前端 未结 5 571
不思量自难忘°
不思量自难忘° 2020-12-29 08:55

I am trying to draw a transparent rectangle in my UIView which has a black border.

My code however creates a completely black rectangle. Here\'s my code so far:

5条回答
  •  礼貌的吻别
    2020-12-29 09:16

    Your code does not require the CGContextSetRGBFillColor call and is missing the CGContextStrokeRect call. With Swift 5, your final draw(_:) implementation should look like this:

    class CustomView: UIView {
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = .white
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func draw(_ rect: CGRect) {
            guard let ctx = UIGraphicsGetCurrentContext() else { return }    
            ctx.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 0.5)
            let rectangle = CGRect(x: 0, y: 100, width: 320, height: 100)
            ctx.stroke(rectangle)
        }
    
    }
    

    As an alternative, if your really want to call CGContextSetRGBFillColor, you also to have call CGContextFillRect. Your final draw(_:) implementation would then look like this with Swift 3:

    class CustomView: UIView {
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = .white
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func draw(_ rect: CGRect) {
            guard let ctx = UIGraphicsGetCurrentContext() else { return }
    
            ctx.setFillColor(red: 1, green: 1, blue: 1, alpha: 0)
            ctx.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 0.5)
    
            let rectangle = CGRect(x: 0, y: 100, width: 320, height: 100)
            ctx.fill(rectangle)
            ctx.stroke(rectangle)
        }
    
    }
    

提交回复
热议问题