Search code examples
iosswiftcalayercgcontext

How to draw String in CGContext?


I am trying to draw a string in the overriden draw method of CALayer (I'm programming for iOS).

override func draw(in ctx: CGContext) {
    let font = UIFont.systemFont(ofSize: 30)
    let string = NSAttributedString(string: "23", attributes: [NSAttributedStringKey.font: font])
    string.draw(at: CGPoint(x: 200, y: 200))
}

This is however not drawing anything (at least nothing is visible). Changing fill and stroke color does not make a difference.

If I draw a line it will show, so the function is being called. I know there is a CATextLayer but I need to draw the string directly. How are you supposed to draw a string in CGContext in the Swift 4 era? No amount of net searching has yielded an answer.


Solution

  • I assume you know all other settings. The key here is you have not make the CGContext as current one. Just add two lines code to solve the problem. Hope you get the answer.

       override func draw(in ctx: CGContext) {
       UIGraphicsPushContext(ctx)
        let font = UIFont.systemFont(ofSize: 30)
        let string = NSAttributedString(string: "23", attributes: [NSAttributedString.Key.font: font])
        string.draw(at: CGPoint(x: 200, y: 200))
       UIGraphicsPopContext()
    }