如何在swift中以编程方式在iPhone上显示透明矩形



我想在一个特定区域周围画一个矩形,在这个区域中我将显示各种视图。

所以矩形必须是透明的。

但我的矩形是不透明的黑色。

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

Plot_DemobackgroundColor设置为.clear:

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

此外,您可能不想直接在UIView上调用.draw——当它被添加到视图层次结构中时,它会自动绘制出来。如果希望它绘制在不同的矩形中,请将参数传递给它并调用setNeedsDisplay,或者添加约束,使其成为所需的大小。

最新更新