OGeek|极客世界-中国程序员成长平台

标题: ios - 怎么画(_rect : CGRect) actually work? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:00
标题: ios - 怎么画(_rect : CGRect) actually work?

我不明白这个函数实际上是如何工作的 如果我想更改“ View ”的背景颜色,我将访问 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()
    }
}



Best Answer-推荐答案


UIView 具有 .backgroundColor 属性。当 UIKit 想要显示 View 时,它会检查 .backgroundColor 属性并用该颜色“填充”背景。

UIColor.green.set()rect.fill() 不会更改背景颜色 View 。

当你重写 draw(_ rect: CGRect) 函数时,UIKit 已经完成了 .backgroundColor 属性的处理,并根据需要填充了背景。 您的代码然后在背景上“绘制一个填充的矩形”。

关于ios - 怎么画(_rect : CGRect) actually work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46772677/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4