0
0
iOS Swiftmobile~5 mins

Canvas for drawing in iOS Swift

Choose your learning style9 modes available
Introduction

A canvas lets you draw shapes, lines, or pictures on the screen. It helps you create custom drawings or designs in your app.

When you want users to draw or doodle on the screen.
To create custom graphics like charts or shapes.
For making simple games that need drawing.
To add signatures or handwriting input.
When you want to show dynamic drawings that change.
Syntax
iOS Swift
class MyView: UIView {
  override func draw(_ rect: CGRect) {
    super.draw(rect)
    let context = UIGraphicsGetCurrentContext()!
    // Drawing code here
  }
}
The draw(_:) method is where you put your drawing code.
Use UIGraphicsGetCurrentContext() to get the canvas to draw on.
Examples
This fills the whole canvas with red color.
iOS Swift
override func draw(_ rect: CGRect) {
  super.draw(rect)
  let context = UIGraphicsGetCurrentContext()!
  context.setFillColor(UIColor.red.cgColor)
  context.fill(rect)
}
This draws a blue line from point (10,10) to (100,100).
iOS Swift
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()
}
Sample App

This app shows a yellow background with a red diagonal line from top-left to bottom-right.

iOS Swift
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)
  }
}
OutputSuccess
Important Notes

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.

Summary

Canvas drawing uses UIView's draw(_:) method.

Get the drawing context with UIGraphicsGetCurrentContext().

Use context methods to draw shapes, lines, and colors.