1

I want to draw a rectangle around a specific area in which I will be displaying various views.

So rectangle must be transparent.

But my rectangle is opaque black.

import UIKit
import Foundation


class ViewController: UIViewController 
{



    override func viewDidLoad()            
    {
            super.viewDidLoad()


        let k = Plot_Demo(frame: CGRect(x: 75, y: 75, width: 150, height: 150))

        k.draw(CGRect(x: 50, y: 50, width: 100, height: 100))

        self.view.addSubview(k)

    }
 }



public class Plot_Demo: UIView
{
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

    public override func draw(_ frame: CGRect) {
        let h = frame.height
        let w = frame.width
        let color:UIColor = UIColor.yellow

        let drect = CGRect(x: (w * 0.25), y: (h * 0.25), width: (w * 0.5), height: (h * 0.5))
        let bpath:UIBezierPath = UIBezierPath(rect: drect)

        color.set()
        bpath.stroke()

        print("it ran")
        NSLog("drawRect has updated the view")
    }
}
Doug Null
  • 7,989
  • 15
  • 69
  • 148

1 Answers1

3

Set the backgroundColor of Plot_Demo to .clear:

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = .clear
}

Also, you probably don't want to be calling .draw on a UIView directly -- it'll get drawn automatically when it's added to the view hierarchy. If you want it to draw in a different rectangle, either pass in parameters to it and call setNeedsDisplay or add constraints so that it is the desired size.

jnpdx
  • 45,847
  • 6
  • 64
  • 94