top of page

37. SwiftUI: View rotation and offset

Writer's picture: Hui WangHui Wang

Today I will show you how to use the rotate and offset functions to mirror a view.


Steps:

  • First, import an image with half the portrait.


  • Then add a ZStack as a container for the subviews.

  • Add an Image and load the image resource with half of the portrait.

ZStack {
    Image("fox-half")
}

  • Add another same Image.

  • Rotate the Image 180 degrees in the horizontal direction.

Image("fox-half")
    .rotation3DEffect(.degrees(180), axis: (x: 1, y: 0, z: 0))

  • Then rotate the Image 180 degrees in the vertical direction.

.rotationEffect(.degrees(180), anchor: .center)

  • Offset the Image horizontally to the right.

.offset(x: 160, y: 0)

  • Finally, move the ZStack to the left so that the entire frame is in the center of the screen.

.offset(x: -80, y: 0)

Source Code:

struct ContentView: View {
    
    var body: some View {
        ZStack {
            Image("fox-half")
            Image("fox-half")
                .rotation3DEffect(.degrees(180), axis: (x: 1, y: 0, z: 0))
                .rotationEffect(.degrees(180), anchor: .center)
                .offset(x: 160, y: 0)
        }
        .offset(x: -80, y: 0)
    }
}

 

Follow me on:

Comments


Never Miss a Post. Subscribe Now!

I am an iOS developer, and I will share some knowledge related to iOS development from time to time.

Thanks for submitting!

© 2022 by (Foks) Hui Wang

bottom of page