Rotate with RotationGesture

Published by @SoNiceInfo at 6/24/2020


RotationGesture is a two-finger operation, and the SwiftUI provides the rotation angle, so you can easily implement the rotation.

Implementing with RotationGesture

To rotate the view with two fingers on the SwiftUI, you can use the rotationEffect.
Here is a rotated image as an example. We have saved an image named ice in the project beforehand.
For image handling, Display Images.

In RotationGesture, the angle is provided in the onChanged.
In order to take advantage of the angle provided, first declare the variable angle and then declare I'm done.
Change the angle of the rotationEffect to the angle (angle) to make it easy to rotate.

The angle provided in onChanged starts at zero.
Therefore, it is implemented by passing the angle to rotationEffect. then when you rotate it again, the View will return to its initial unrotated state.

To start the rotation from the previous rotation position, you can uncomment the variable in your code and enable lastAngle.
Then comment out self.angle = angle
You can implement onEnded to start at the previous rotation position by saving the previous last angle in lastAngle and adding it to the angle you can get in onChanged.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView: View {
    @State private var angle: Angle = .degrees(.zero)
    // @State private var lastAngle: Angle = .degrees(.zero)
    @State private var length : CGFloat = 400

    var body: some View {
        Image("ice")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .clipShape(Circle())
            .frame(width: length, height: length)
            .rotationEffect(self.angle)
            .gesture(RotationGesture()
                .onChanged{ angle in
                    self.angle = angle
                    // self.angle = angle + self.lastAngle
                }
                // .onEnded { angle in
                //     self.lastAngle = self.angle
                // }
            )
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

References

Gestures | Apple Developer Documentation


    I released iOS App!

    ToDo App

    Visualize Activity, Data sharing with iCloud, Dark mode supported.

    リリースしたToDoアプリのスクリーンショット

    IP Address bookmark.

    Check and bookamrk IP address of all interfaces with geolocation.

    リリースしたIPアドレス保存アプリのスクリーンショット