Introduction
A canvas lets you draw shapes, lines, or pictures on the screen. It helps you create custom drawings or designs in your app.
A canvas lets you draw shapes, lines, or pictures on the screen. It helps you create custom drawings or designs in your app.
class MyView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) let context = UIGraphicsGetCurrentContext()! // Drawing code here } }
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(UIColor.red.cgColor)
context.fill(rect)
}override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
context.setStrokeColor(UIColor.blue.cgColor)
context.setLineWidth(5)
context.move(to: CGPoint(x: 10, y: 10))
context.addLine(to: CGPoint(x: 100, y: 100))
context.strokePath()
}This app shows a yellow background with a red diagonal line from top-left to bottom-right.
import UIKit class DrawingView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.setFillColor(UIColor.yellow.cgColor) context.fill(rect) context.setStrokeColor(UIColor.red.cgColor) context.setLineWidth(4) context.move(to: CGPoint(x: 20, y: 20)) context.addLine(to: CGPoint(x: rect.width - 20, y: rect.height - 20)) context.strokePath() } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let drawingView = DrawingView(frame: view.bounds) drawingView.backgroundColor = .white view.addSubview(drawingView) } }
Always call super.draw(rect) if you override draw in a subclass that already draws something.
Drawing happens only inside the draw(_:) method.
Use setNeedsDisplay() to refresh the canvas and redraw.
Canvas drawing uses UIView's draw(_:) method.
Get the drawing context with UIGraphicsGetCurrentContext().
Use context methods to draw shapes, lines, and colors.
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.setFillColor(UIColor.red.cgColor)
ctx.fill(CGRect(x: 10, y: 10, width: 100, height: 50))
}override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
ctx.setFillColor(UIColor.blue.cgColor)
ctx.fillEllipse(in: CGRect(x: 20, y: 20, width: 80, height: 80))
}Pass the test and this pattern moves unknown