How do I draw custom views with Core Graphics in Swift?

In Swift, you can create custom views using Core Graphics by subclassing UIView and overriding the draw method. This allows you to perform custom drawing, such as rendering shapes, gradients, and images, directly onto the view.

Here's a simple example of how to create a custom UIView that draws a red rectangle and a blue circle:

// CustomView.swift import UIKit class CustomView: UIView { override func draw(_ rect: CGRect) { // Get the current context guard let context = UIGraphicsGetCurrentContext() else { return } // Set the fill color for the rectangle context.setFillColor(UIColor.red.cgColor) // Draw a rectangle context.fill(CGRect(x: 20, y: 20, width: 100, height: 100)) // Set the fill color for the circle context.setFillColor(UIColor.blue.cgColor) // Draw a circle context.fillEllipse(in: CGRect(x: 150, y: 20, width: 100, height: 100)) } }

Swift Core Graphics Custom Views UIView Drawing