70 lines
3.1 KiB
Swift
70 lines
3.1 KiB
Swift
import AppKit
|
|
import SwiftUI
|
|
|
|
/// Small Core Graphics arcs avoid creating a SwiftUI path-rendering surface for every gauge.
|
|
struct NativeMetricRing: NSViewRepresentable {
|
|
let value: Double
|
|
let color: Color
|
|
let lineWidth: CGFloat
|
|
let trackOpacity: Double
|
|
let inset: CGFloat
|
|
|
|
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, context: Context) -> CGSize? {
|
|
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
|
|
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
|
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
|
|
}
|
|
|
|
func makeNSView(context: Context) -> RingView { RingView() }
|
|
func updateNSView(_ view: RingView, context: Context) {
|
|
view.configure(Input(value: value.isFinite ? min(1, max(0, value)) : 0, color: color,
|
|
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset))
|
|
}
|
|
struct Input: Equatable {
|
|
let value: Double
|
|
let color: Color
|
|
let lineWidth: CGFloat
|
|
let trackOpacity: Double
|
|
let inset: CGFloat
|
|
}
|
|
final class RingView: NSView {
|
|
private(set) var input: Input?
|
|
override var isFlipped: Bool { true }
|
|
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
|
init() {
|
|
super.init(frame: .zero)
|
|
wantsLayer = true; layerContentsRedrawPolicy = .onSetNeedsDisplay
|
|
setAccessibilityElement(false)
|
|
}
|
|
required init?(coder: NSCoder) { nil }
|
|
func configure(_ value: Input) {
|
|
guard value != input else { return }
|
|
input = value; needsDisplay = true
|
|
}
|
|
override func setFrameSize(_ newSize: NSSize) {
|
|
let changed = newSize != frame.size
|
|
super.setFrameSize(newSize)
|
|
if changed { needsDisplay = true }
|
|
}
|
|
override func viewDidChangeEffectiveAppearance() {
|
|
super.viewDidChangeEffectiveAppearance(); needsDisplay = true
|
|
}
|
|
override func draw(_ dirtyRect: NSRect) {
|
|
guard let input, let context = NSGraphicsContext.current?.cgContext else { return }
|
|
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
|
|
guard radius > 0 else { return }
|
|
let center = CGPoint(x: bounds.midX, y: bounds.midY)
|
|
let tint = NSColor(input.color)
|
|
context.saveGState(); defer { context.restoreGState() }
|
|
context.setLineWidth(input.lineWidth); context.setLineCap(.round)
|
|
context.setStrokeColor(tint.withAlphaComponent(input.trackOpacity).cgColor)
|
|
context.strokeEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))
|
|
guard input.value > 0 else { return }
|
|
context.setStrokeColor(tint.cgColor)
|
|
context.addArc(center: center, radius: radius, startAngle: -.pi / 2,
|
|
endAngle: -.pi / 2 + 2 * .pi * input.value, clockwise: false)
|
|
context.strokePath()
|
|
}
|
|
}
|
|
}
|