簡體   English   中英

draw(_ rect:CGRect)實際如何工作?

[英]How draw(_ rect: CGRect) actually work?

我不了解此功能的實際工作方式。如果我想更改“視圖”的背景顏色,我將進入“視圖”的背景屬性並更改其值

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屬性並用該顏色“填充”背景。

UIColor.green.set()rect.fill()不會更改視圖的背景色。

當您重寫draw(_ rect: CGRect)函數時,UIKit已經完成了對.backgroundColor屬性的處理,並根據需要填充了背景。 然后, 您的代碼在背景上“繪制一個填充的矩形”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM