iosswiftdrawbackground-colorcgrect

Draw rectangle with clear background on top of imageView


I am trying to draw a rectangle with a random border color with a clear background on top of an imageView. I need to loop through a set of co-ordinates and add appropriate rectangles to my image. I can't manage to get the rectangle background colour to be clear. Code below:

// the draw class

class Draw: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        let h = rect.height
        let w = rect.width
        let color:UIColor = Palette.getRandomColour()

        //var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
        let drect = CGRect(x: rect.minX ,y: rect.minY , width: w, height: h)
        let bpath:UIBezierPath = UIBezierPath(rect: drect)
        UIColor.clear.setFill()
        color.set()
        bpath.stroke()

        print("it ran")

        NSLog("drawRect has updated the view")                
    }  
}

// and in my viewDidLoad

for bp in sbp {
    if let master = Bodyparts.getID(bp.masterid) {
        let width  = master.x2 - master.x1
        let height = master.y2 - master.y1
        let k = Draw(frame: CGRect(origin: CGPoint(x: master.x1, y: master.y1), size: CGSize(width: width, height: height)))
        self.imgView.addSubview(k)
    }                        
}

Solution

  • You need to set the background to clear. Here is a playground that you can copy and paste:

    import PlaygroundSupport
    import UIKit
    
    class Draw: UIView {
    
      override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
      }
    
      required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
      }
    
      override func draw(_ rect: CGRect) {
        let h = rect.height
        let w = rect.width
        let color:UIColor = .red
        let drect = CGRect(x: rect.minX ,y: rect.minY , width: w, height: h)
        let bpath:UIBezierPath = UIBezierPath(rect: drect)
        UIColor.clear.setFill()
        color.set()
        bpath.stroke()
      }
    }
    let d = Draw(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    view.backgroundColor = .green
    view.addSubview(d)
    PlaygroundPage.current.liveView = view