With Swift 4 and iOS 11, according to your needs, you can choose one of two ways to solve your problem.
# 1. Draw and populate the specified CGRect instance with the CGRect instance inside the UIView subclass using the UIRectFill(_:) function
UIKit provides the UIRectFill(_:) function. UIRectFill(_:) has the following declaration:
func UIRectFill(_ rect: CGRect)
Fills the specified rectangle with the current color.
The following pad code shows how to use 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. Draw and populate the specified CGRect instance with the CGRect instance inside the UIView subclass using the CGContext fill(_:) method
CGContext has a method called fill(_:) . fill(_:) has the following declaration:
func fill(_ rect: CGRect)
Colors the area contained in the provided rectangle using the fill color in the current state of the graphic.
The following playground code shows how to use 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
Imanou petit
source share