swiftmacosstatusbarappkit

Scaling a PDF image for NSStatusItem image


I'm trying to create a macOS app with a status bar item that uses a PDF rather than PNG image, however when I use that image it's overscaled and the entire status item is black. I can't find a way to scale the image so that it fits with the rest of the mac status bar items.

Icon

Assets.xcassets

image of scode showing the pdf icon of a globe

AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        if let button = statusItem.button {
          button.image = NSImage(named:NSImage.Name("status-logo"))
          button.action = #selector(printQuote(_:))
        }
    }

    @objc func printQuote(_ sender: Any?) {
      let quoteText = "Never put off until tomorrow what you can do the day after tomorrow."
      let quoteAuthor = "Mark Twain"

      print("\(quoteText) — \(quoteAuthor)")
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}

Expectation

A picture of the icon

Reality

A screenshot showing a black square for my icon alongside other status bar items


Solution

  • You should resize your pdf so that it fits inside statusItem's button like this:

        guard let logo = NSImage(named: NSImage.Name("status-logo")) else { return }
    
        let resizedLogo = NSImage(size: NSSize(width: 18, height: 18), flipped: false) { (dstRect) -> Bool in
            logo.draw(in: dstRect)
            return true
        }
    

    Then set button.image = resizedLogo