XAMPPRocky
XAMPPRocky

Reputation: 3619

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

Upvotes: 2

Views: 516

Answers (2)

N.K.
N.K.

Reputation: 510

For a more simpler solution, you can:

  1. Add your status-logo image to your Assets.xcassets in Xcode.
  2. Resize the image as follows:
// Accessing image from assets
let iconImage = NSImage.statusLogo
// Resizing icon
let newSize = NSSize(width: 18, height: 18)
let resizedIcon = NSImage(size: newSize, flipped: false) { (dstRect) -> Bool in
    statusLogo.draw(in: dstRect)
    return true
}

  1. And finally assign button.image = resizedLogo.

Upvotes: 0

Loengard
Loengard

Reputation: 441

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

Upvotes: 6

Related Questions