How do I draw a rectangle with equal line widths into an NSStatusItemButton?

550 Views Asked by At

The following code draws a rectangle with NSBezierPath into an NSImage, which is then set as the image for an NSStatusItemButton.

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
                NSColor.black.setStroke()

                let path = NSBezierPath()
                path.appendRect(NSRect(
                    x: NSMinX(dstRect),
                    y: NSMinY(dstRect),
                    width: 10,
                    height: 10))
                path.stroke()

                return true
        })

        statusItem.button?.image = statusItemImage
    }

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

In the menu bar, it looks like this:

enter image description here

The left and bottom edge of the rectangle have a different width than the right and top edge.

How do I get a rectangle with equal line widths?

1

There are 1 best solutions below

1
Sombre Osmo'z On

You have to set a lineWidth for your path:

/// The new rectangle
let new = CGRect(origin: dstRect.origin,
                 size: .init(width: 10, height: 10))

let path = NSBezierPath(rect: new)
// The line width size 
path.lineWidth = 0.1

path.stroke()