Search code examples
swiftuipixel-density

What is the recommended way to convert between pixels and points in SwiftUI?


I want to display a QR code in SwiftUI. The code is generated as a CGImage via CIImage. I don't want to scale it to the full size available because if the scaling factor isn't an integer there may be fuzzy boundaries between the QR modules. So I need a way to convert between iOS display points which I can get with GeometryReader and physical points. I've found a few search "hits" about reading the screen scale from a UIView, but not how I can get this scale in SwiftUI.

There a few more hits which just say the scale is 3 on all modern iPhones, and as I'm targeting iOS 15+ I think I can safely assume it's always 3 for now, but what if Apple bring out even higher pixel densities in future?


Solution

  • You can get displayScale using the Environment property wrapper.

    struct ContentView: View {
        @Environment(\.displayScale) var displayScale
    
        var body: some View {
            Text("display scale: \(displayScale)")
        }
    }
    

    Consult EnvironmentValues to see what else SwiftUI provides in the “environment”.