swiftappkit

How do I draw text into an NSImage?


How do I draw text into an NSImage with Swift and the AppKit framework? My target is a macOS application.

I would also appreciate any resources where things like this are explained. I couldn't find examples or explanations in the Apple developer documentation.

The following code contains a comment to illustrate what I want to do. It shows the NSImage in a menubar item.

import Cocoa

class ViewController: NSViewController {
    let statusItem: NSStatusItem = NSStatusBar.system.statusItem(
        withLength: NSStatusItem.squareLength)

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageSize = NSSize.init(width: 18.0, height: 18.0)

        let statusItemImage = NSImage(
            size: imageSize,
            flipped: false,
            drawingHandler: { (dstRect: NSRect) -> Bool in
                // How do I draw text into this NSImage?
                return true
        })

        statusItem.button?.image = statusItemImage
    }

    override var representedObject: Any? {
        didSet {
        }
    }
}

Solution

  • Use the NSString's draw(in:) method inside NSImage's drawingHandler:

    let foo: NSString = "a"
    foo.draw(in: dstRect)
    

    Example:

    let imageSize = NSSize.init(width: 18.0, height: 18.0)
    
    let statusItemImage = NSImage(
        size: imageSize,
        flipped: false,
        drawingHandler: { (dstRect: NSRect) -> Bool in
            let foo: NSString = "a"
            foo.draw(in: dstRect)
            return true
        })