简体   繁体   中英

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

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:

在此处输入图像描述

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM