如何在Swift中将UIBezierPath椭圆居中在未知宽度和高度的视图中?

问题描述:

我在自定义UIView中使用绘图函数来创建自定义纹理。问题是宽度和高度由UIStackView确定。当我创建视图时,我使用CustomView(frame: CGRect(x: 0, y: 0, width: 50, height: 50, color: color)如果实际宽度和高度在自定义UIView使用绘图函数时未知。有没有办法保证UIBezierPath在UIStackView给出的范围内?如何在Swift中将UIBezierPath椭圆居中在未知宽度和高度的视图中?

import Foundation 
import UIKit 
class CustomView: UIView { 

     let color: UIColor 

     required init(coder aDecoder: NSCoder) { 
      color = UIColor() 
      super.init(coder: aDecoder)! 
     } 
     init(frame: CGRect, color: UIColor) { 
      self.color = color 
      super.init(frame: frame) 
      self.backgroundColor = UIColor.init(hexString: CustomColors.pale_blue) 
     } 

     override func draw(_ rect: CGRect) { 

      color.setFill() 
      color.setStroke() 
      let width = Int(rect.size.width) 
      let height = Int(rect.size.height) 
      let yValue = Int(rect.origin.y) 
      let xValue = Int(rect.origin.x) 
      let rectBottom = UIBezierPath(rect: CGRect(x: xValue , y: yValue + height - (height/4), width: width, height: height/4)) 
      let ovalTop = UIBezierPath(ovalIn: CGRect(x: xValue + (width/4), y:yValue + (height/3), width: width/2, height: height/2)) 
      rectBottom.stroke() 
      rectBottom.fill() 
      ovalTop.fill() 
      ovalTop.stroke() 
     } 
} 

在调用绘图方法时,布局已经发生。只需看看draw()中的self.bounds即可。 要清楚,不要看通过绘制的矩形来确定您的几何。如果您只想重绘需要更新的位,则只能使用该矩形。