我如何在NSStatusItemButton中绘制线宽相等的矩形?

问题描述 投票:-1回答:1

以下代码将带有NSBezierPath的矩形绘制到NSImage中,然后将其设置为imageNSStatusItemButton

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 {
        }
    }
}

在菜单栏中,看起来像这样:

enter image description here

[矩形的左边缘和下边缘的宽度与右边缘和上边缘的宽度不同。

如何获得线宽相等的矩形?

swift appkit nsstatusitem nsbezierpath
1个回答
0
投票

您必须为路径设置lineWidth

/// 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()
© www.soinside.com 2019 - 2024. All rights reserved.