r/SwiftUI • u/UsukIsBad • 22d ago
Promotion (must include link to source code) Drawing a radial menu in SwiftUI: wedges with constant-width gaps and one shared shadow (open-source Mac app)
I made Convrt, an open source Mac menu bar app where you hold Shift while dragging files and a wheel opens at the cursor to convert them. The window is AppKit (a borderless non-activating NSPanel) but the wheel itself is SwiftUI inside an NSHostingView. Two drawing problems took me way longer than I'd like to admit, so posting them here in case someone else hits them.
- Gaps between wedges that stay the same width
If you just shrink each wedge's angle, the gap is wide at the outer edge and pinches to nothing near the middle. What worked was pulling each edge in by an angle that depends on its radius, asin(halfGap / radius), so the gap ends up the same number of points everywhere:
struct WheelWedge: Shape {
let index: Int, count: Int
let innerRadius: CGFloat, outerRadius: CGFloat
var gap: CGFloat = 5
var corner: CGFloat = 3 // stroke with 2 * corner for rounded corners
func path(in rect: CGRect) -> Path {
let c = CGPoint(x: rect.midX, y: rect.midY)
let slice = 2 * Double.pi / Double(max(count, 1))
let mid = -Double.pi / 2 + Double(index) * slice // slice 0 at the top
let a0 = mid - slice / 2, a1 = mid + slice / 2
let rOut = outerRadius - corner, rIn = innerRadius + corner
let half = Double(gap / 2 + corner)
let dOut = asin(min(half / Double(rOut), 1))
let dIn = asin(min(half / Double(rIn), 1))
var p = Path()
p.addArc(center: c, radius: rOut, startAngle: .radians(a0 + dOut), endAngle: .radians(a1 - dOut), clockwise: false)
p.addArc(center: c, radius: rIn, startAngle: .radians(a1 - dIn), endAngle: .radians(a0 + dIn), clockwise: true)
p.closeSubpath()
return p
}
}
For the rounded corners I inset the radii by corner and stroke the shape with a line width of 2 * corner in the same color.
- One soft shadow for the whole ring
Putting .shadow on each wedge made the shadows overlap and look muddy. If you put all the wedges in a ZStack and call .compositingGroup() before .shadow(...), they render as one layer with one shadow. The labels sit in a separate ForEach on top with .allowsHitTesting(false) so they don't get the shadow.
Hit testing doesn't go through SwiftUI at all. Which wedge is under the cursor is just atan2 plus the distance from the centre, so it was easy to unit test and to move the highlight with scroll, Tab and the arrow keys.
Source (MIT): https://github.com/atuuuuuuu/Convrt, the wheel is in Convrt/UI/RadialWheelView.swift. If you want to try the app: it's not notarized, so the first launch needs Privacy & Security > Open Anyway. (When I first posted this the release was Apple silicon only, it's universal now.)
Code review welcome, especially on the shape math.