0
我在自定義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()
}
}