以下代码将带有NSBezierPath
的矩形绘制到NSImage
中,然后将其设置为image
的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 {
}
}
}
在菜单栏中,看起来像这样:
[矩形的左边缘和下边缘的宽度与右边缘和上边缘的宽度不同。
如何获得线宽相等的矩形?
您必须为路径设置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()