菜鸟教程小白 发表于 2022-12-11 19:00:43

ios - 怎么画(_rect : CGRect) actually work?


                                            <p><p>我不明白这个函数实际上是如何工作的
如果我想更改“ View ”的背景颜色,我将访问 View 的背景属性并更改它的值</p>

<pre><code>let containerView = CustomView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
containerView.backgroundColor = UIColor.blue
</code></pre>

<p>但是当我想在 draw() 函数中改变矩形的颜色时
我只是调用 UIColor.green.set() 函数。为什么这个函数会改变矩形的颜色</p>

<pre><code>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()// &lt;- Why this line change rect color ?
      rect.fill()
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><code>UIView</code> 具有 <code>.backgroundColor</code> 属性。当 UIKit 想要显示 View 时,它会检查 <code>.backgroundColor</code> 属性并用该颜色“填充”背景。</p>

<p><code>UIColor.green.set()</code> 和 <code>rect.fill()</code> 不会<strong><em>更改</em></strong>背景颜色 View 。</p>

<p>当你重写 <code>draw(_ rect: CGRect)</code> 函数时,UIKit 已经完成了 <code>.backgroundColor</code> 属性的处理,并根据需要填充了背景。 <strong><em>您的</em></strong>代码然后在背景上“绘制一个填充的矩形”。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 怎么画(_rect : CGRect) actually work?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/46772677/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/46772677/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 怎么画(_rect : CGRect) actually work?