NEW: Master Swift design patterns with my latest book! >>

How to draw a square using Core Graphics: addRect()

Written by Paul Hudson    @twostraws

You can draw a square (or indeed any size of rectangle) using the addRect() Core Graphics function. There's a little bit of set up work required, such as creating a context big enough to hold the square and setting up colors, but the code below does everything you need:

let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
    ctx.cgContext.setFillColor(UIColor.red.cgColor)
    ctx.cgContext.setStrokeColor(UIColor.green.cgColor)
    ctx.cgContext.setLineWidth(10)

    let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
    ctx.cgContext.addRect(rectangle)
    ctx.cgContext.drawPath(using: .fillStroke)
}

Important note: when setting a line width using setLineWidth(), the center of the border is the edge of your path. This means our board will be 5 points inside the rectangle and 5 points outside, because we have a total border width of 10 points. Because the square's path is the same size as the context, this means the outside part of the border will be clipped.

Available from iOS 4.0 – see Hacking with Swift tutorial 27

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

Click here to visit the Hacking with Swift store >>