Last active
June 4, 2024 15:07
-
-
Save thecoolwinter/993d898b6aa555511a5ad4a0a2fb3ef9 to your computer and use it in GitHub Desktop.
Quick dirty NSLabel class for drawing text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSLabel.swift | |
// | |
// | |
// Created by Khan Winter on 4/8/22. | |
// | |
import AppKit | |
class NSLabel: NSView { | |
var string: String | |
var font: NSFont | |
var backgroundColor: NSColor? | |
override init(frame frameRect: NSRect) { | |
self.string = "" | |
self.font = NSFont.systemFont(ofSize: 12, weight: .regular) | |
super.init(frame: frameRect) | |
} | |
init(string: String) { | |
self.string = string | |
self.font = NSFont.systemFont(ofSize: 12, weight: .regular) | |
super.init(frame: .zero) | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override var intrinsicContentSize: NSSize { | |
makeAttributedString().size() | |
} | |
override func draw(_ dirtyRect: NSRect) { | |
guard let context = NSGraphicsContext.current?.cgContext else { return } | |
context.saveGState() | |
if let backgroundColor { | |
context.setFillColor(backgroundColor.cgColor) | |
context.fill([NSRect(origin: .zero, size: self.frame.size)]) | |
} | |
let attributedString = makeAttributedString() | |
let size = attributedString.size() | |
let yPos = (self.frame.size.height - size.height)/2 | |
let rect = NSRect(x: 0, y: yPos, width: self.frame.size.width, height: size.height) | |
attributedString.draw(in: rect) | |
context.restoreGState() | |
} | |
private func makeAttributedString() -> NSAttributedString { | |
// swiftlint:disable:next force_cast | |
let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle | |
paragraphStyle.alignment = .center | |
paragraphStyle.lineBreakMode = .byTruncatingTail | |
return NSAttributedString( | |
string: string, | |
attributes: [.font: font, .paragraphStyle: paragraphStyle] | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment