使用 Swift 5.1 和 iOS 13,您可以选择以下两种方式之一来解决您的问题。
#1。使用UIRectFill(_:) 函数在UIView 子类中使用UIColor 实例绘制并填充指定的CGRect 实例
UIKit 提供了一个UIRectFill(_:) 函数。 UIRectFill(_:) 有以下声明:
func UIRectFill(_ rect: CGRect)
用当前颜色填充指定的矩形。
以下 Playground 代码展示了如何使用UIRectFill(_:):
import UIKit
import PlaygroundSupport
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.green
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let bottomRect = CGRect(
origin: CGPoint(x: rect.origin.x, y: rect.height / 2),
size: CGSize(width: rect.size.width, height: rect.size.height / 2)
)
UIColor.red.set()
UIRectFill(bottomRect)
}
}
let view = CustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
PlaygroundPage.current.liveView = view
#2。使用CGContext 的fill(_:) 方法在UIView 子类中使用UIColor 实例绘制并填充指定的CGRect 实例
CGContext 有一个名为fill(_:) 的方法。 fill(_:) 有以下声明:
func fill(_ rect: CGRect)
使用当前图形状态下的填充颜色绘制包含在提供的矩形内的区域。
以下 Playground 代码展示了如何使用fill(_:):
import UIKit
import PlaygroundSupport
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.green
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let bottomRect = CGRect(
origin: CGPoint(x: rect.origin.x, y: rect.height / 2),
size: CGSize(width: rect.size.width, height: rect.size.height / 2)
)
UIColor.red.set()
guard let context = UIGraphicsGetCurrentContext() else { return }
context.fill(bottomRect)
}
}
let view = CustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
PlaygroundPage.current.liveView = view