draw(_ rect: CGRect) 是如何工作的?
How draw(_ rect: CGRect) actually work?
我不明白这个功能是如何工作的
如果我想更改 "View" 的背景颜色,我将访问视图的背景 属性 并更改它的值
let containerView = CustomView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
containerView.backgroundColor = UIColor.blue
但是当我想在 draw() 函数中改变矩形的颜色时
我只是调用 UIColor.green.set() 函数。为什么这个函数会改变矩形的颜色
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
let rect = UIBezierPath(roundedRect: CGRect(x: 150, y: 150, width: 100, height: 100), cornerRadius: 5.0)
UIColor.green.set() // <- Why this line change rect color ?
rect.fill()
}
}
一个UIView
有一个.backgroundColor
属性。当 UIKit 想要显示视图时,它会检查 .backgroundColor
属性 和 "fills" 具有该颜色的背景。
UIColor.green.set()
和 rect.fill()
不会 更改 视图的背景颜色。
当您覆盖 draw(_ rect: CGRect)
函数时,UIKit 已经完成了 .backgroundColor
属性 的处理,并根据需要填充背景。 你的代码然后在后台"draws a filled rectangle"。
我不明白这个功能是如何工作的 如果我想更改 "View" 的背景颜色,我将访问视图的背景 属性 并更改它的值
let containerView = CustomView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
containerView.backgroundColor = UIColor.blue
但是当我想在 draw() 函数中改变矩形的颜色时 我只是调用 UIColor.green.set() 函数。为什么这个函数会改变矩形的颜色
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
let rect = UIBezierPath(roundedRect: CGRect(x: 150, y: 150, width: 100, height: 100), cornerRadius: 5.0)
UIColor.green.set() // <- Why this line change rect color ?
rect.fill()
}
}
一个UIView
有一个.backgroundColor
属性。当 UIKit 想要显示视图时,它会检查 .backgroundColor
属性 和 "fills" 具有该颜色的背景。
UIColor.green.set()
和 rect.fill()
不会 更改 视图的背景颜色。
当您覆盖 draw(_ rect: CGRect)
函数时,UIKit 已经完成了 .backgroundColor
属性 的处理,并根据需要填充背景。 你的代码然后在后台"draws a filled rectangle"。