Episode #288


Series: Dive Into Core Graphics

9 minutes
Published on July 21, 2017

This video is only available to subscribers. Get access to this video and 490 others.

In this episode, Sam shows how to draw text using Core Graphics. With this technique you can easily add text to images for pre-rendering, a technique we will see in another episode in this series.


Setting up

We will just fill our view with white, then define a string we can draw.

guard let context = UIGraphicsGetCurrentContext() else { return }

let colorSpace = CGColorSpaceCreateDeviceRGB()
let color = CGColor(colorSpace: colorSpace, components: [1, 1, 1, 1])!


let string = "Hello World"

Defining Text Attributes

To configure text color, font, alignment, and other text attributes, we will use NSAttributedString. This takes a dictionary of attributes to apply to the string.

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center

let attributes: [String: Any] = [
    NSFontAttributeName: UIFont.systemFont(ofSize: 40),
    NSForegroundColorAttributeName: UIColor.blue,
    NSParagraphStyleAttributeName: paragraph

Using NSString’s Drawing Method

NSString can draw itself, which is the simplest approach.

(string as NSString).draw(at: CGPoint(x: 20, y: 20), withAttributes: attributes)

Drawing with NSAttributedString

We can also draw an attributed string similarly:

let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
    value: UIFont.systemFont(ofSize: 40, weight: UIFontWeightBold),
    range: NSRange(location: 6, length: 5))

let size = attributedString.size()
attributedString.draw(in: AVMakeRect(aspectRatio: size, insideRect: bounds))

Drawing with UILabel

Another quick way to do this (on iOS) is top leverage UILabel’s drawing.

let label = UILabel()
label.attributedText = attributedString
label.drawText(in: bounds)

This episode uses Swift 3.0, Xcode 8.3.

Comments are temporarily disabled.