您的代码不需要CGContextSetRGBFillColor
调用并且缺少CGContextStrokeRect
调用。使用 Swift 5,您的最终draw(_:)
实现应该如下所示:
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)
}
}
作为替代方案,如果你真的想打电话CGContextSetRGBFillColor
,你也可以打电话CGContextFillRect
。使用 Swift 3,您的最终draw(_:)
实现将如下所示:
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)
}
}