简体   繁体   English

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

[英]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 .以下代码使用NSBezierPath将矩形绘制到NSImage中,然后将其设置为NSStatusItemButtonimage

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:您必须为路径设置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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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