Drawing shapes with Core Graphics Tutorial

Core Graphics is an API included in both Cocoa and Cocoa Touch. It allows you to draw graphic objects on the graphic destination. In this tutorial we will draw some basic shapes such as a rectangle or a circle. This tutorial is made for iOS 9 with Xcode 7.

Open Xcode and create a new Single View Application. For product name, use IOS9DrawShapesTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and drag three Buttons from the Object Library to the top section of the main View. Align them horizontally and give them a title of "Lines, Rectangle, Circle". The Storyboard should look like this.

Select each button and go to the Attributes Inspector. In the View section give the button from left to right a tag of 0,1 and 2. The tag field is needed later on so we will know which button is pressed.

Open The Assistant Editor and make sure the ViewController.swift file is visible. Ctrl And Drag from the "Lines" button to the ViewController class and create the following Action

Select the other buttons and Ctrl and drag to the IBAction method inside the ViewController class. Pressing each button will execute the IBAction method. The drawing will take place inside a custom View. Add a New File to the project. Choose File -> New File -> iOS -> Source -> Cocoa Touch Class. Name the class ShapeView and make it a subclass of UIView.

Go to the ShapeView.swift file and add the following property.

var currentShapeType: Int = 0

The currentShapeType property is used to choose the right method to draw the corresponding object. Next add the following init methods

init(frame: CGRect, shape: Int) {
    super.init(frame: frame)
    self.currentShapeType = shape
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")

When the custom view is initialised, the tag field is given which determines the shape type. the drawRect method is where the custom drawing takes place.

override func drawRect(rect: CGRect) {
    switch currentShapeType {
    case 0: drawLines()
    case 1: drawRectangle()
    case 2: drawCircle()
    default: print("default")

Next, implement the drawing methods

func drawLines() {
    let ctx = UIGraphicsGetCurrentContext()
    CGContextMoveToPoint(ctx, 20.0, 20.0)
    CGContextAddLineToPoint(ctx, 250.0, 100.0)
    CGContextAddLineToPoint(ctx, 100.0, 200.0)
    CGContextSetLineWidth(ctx, 5)
func drawRectangle() {
    let center = CGPointMake(self.frame.size.width / 2.0, self.frame.size.height / 2.0)
    let rectangleWidth:CGFloat = 100.0
    let rectangleHeight:CGFloat = 100.0
    let ctx = UIGraphicsGetCurrentContext()
    CGContextAddRect(ctx, CGRectMake(center.x - (0.5 * rectangleWidth), center.y - (0.5 * rectangleHeight), rectangleWidth, rectangleHeight))
    CGContextSetLineWidth(ctx, 10)
    CGContextSetStrokeColorWithColor(ctx, UIColor.grayColor().CGColor)
    CGContextSetFillColorWithColor(ctx, UIColor.greenColor().CGColor)
    CGContextAddRect(ctx, CGRectMake(center.x - (0.5 * rectangleWidth), center.y - (0.5 * rectangleHeight), rectangleWidth, rectangleHeight))
func drawCircle() {
    let center = CGPointMake(self.frame.size.width / 2.0, self.frame.size.height / 2.0)
    let ctx = UIGraphicsGetCurrentContext()
    CGContextSetLineWidth(ctx, 5)
    let x:CGFloat = center.x
    let y:CGFloat = center.y
    let radius: CGFloat = 100.0
    let endAngle: CGFloat = CGFloat(2 * M_PI)
    CGContextAddArc(ctx, x, y, radius, 0, endAngle, 0)
  1. he Graphic Context is your graphic destination. If you want to draw on a view, the view is your Graphic Context. We need to get a reference  to the Graphics Context.
  2. A path is a set of lines, arcs and curves you can draw on the current graphic context to build complex objects. Here we draw some lines and set the line width to 5.
  3. The path is closed and drawn to the graphics context.
  4. With CGContextAddRect a rectangle is drawn. the outline stroke color is gray.
  5. Here the same rectangle is defined, with a fill color of green
  6. With CGContextAddArc a circle is drawn

 Next, implement the buttonPressed method in the ViewController.swift file

@IBAction func buttonPressed(sender: UIButton) {
    let myView = ShapeView(frame: CGRectMake(50, 200, 280, 250), shape: sender.tag)
    myView.backgroundColor = UIColor.cyanColor()

Build and Run and click on each button to draw the different shapes.

You can download the source code of the IOS9DrawShapesTutorial at the ioscreator repository on Github.