In SwiftUI, how to rotate a background image when orientation changes

I've got some views that have background images, and I would like to switch those images to different images, when the orientation changes. I'm following this example to track when the orientation changes:

https://www.hackingwithswift.com/quick-start/swiftui/how-to-detect-device-rotation

So this gives me a way to track when orientation changes, but I can't find anywhere to use that information because the Views will already have drawn by the time I can execute any code.

Replies

Image rotation is automatic. So this applies if you want to change image when rotating.

Did you try adapting the proposed code:

struct ContentView: View {
    
    @State private var orientation = UIDeviceOrientation.unknown

    var body: some View {
        Group {
            if orientation.isPortrait {
                Image("ImagePortrait")
            } else if orientation.isLandscape {
                Image("ImageLandscape")
            } else if orientation.isFlat {
                Image("ImageFlat")
            } else {
                Image("NoImage")
            }
        }
        .onRotate { newOrientation in
            orientation = newOrientation
        }
// Continue view definition
}

Could you show the code where you define background image, so that we can see exactly how to fit.

You should probably define a computed var for the image:

struct ContentView: View {
    
    @State private var orientation = UIDeviceOrientation.unknown
    private var myImage : Image {
        if orientation.isPortrait {
            return Image("ImagePortrait")
        } else if orientation.isLandscape {
            return Image("ImageLandscape")
        } else if orientation.isFlat {
            return Image("ImageFlat")
        } else {
            return Image("NoImage")
        }
    }
    
    var body: some View {

            VStack{
                Text("Hello")
            }
             onRotate { newOrientation in orientation = newOrientation }
            .background(myImage)
    }
}