When performing custom layout in AppKit
, it's essential that you pixel align frames using methods like backingAlignedRect
. The alignment differs depending on the backingScaleFactor
of the parent window.
When building custom Layouts
in SwiftUI, how should you compute the alignment of a subview.frame
in placeSubviews()
before calling subview.place(...)
?
Surprisingly, I haven't seen any mention of this in the WWDC videos. However, if I create a Rectangle
of width 1px
and then position it on fractional coordinates, I get a blurry view, as I would expect.
Rounding to whole numbers works, but on Retina screens you should be able to round to 0.5
as well.
func placeSubviews(
in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout Void
) {
// This should be backing aligned based on the parent window's backing scale factor.
var frame = CGRect(
x: 10.3,
y: 10.8,
width: 300.6,
height: 300.1
)
subview.place(
at: frame.origin,
anchor: .topLeading,
proposal: ProposedViewSize(frame.size)
)
}