Perform Multiple Simultaneous Gestures with simultaneousGesture

Published by @SoNiceInfo at 6/24/2020


Xcode window using simultaneousGesture.

By using simultaneousGesture, you can create multiple simultaneous gestures.
Here is an example of how to zoom and rotate an image at the same time.

Rotate and Zoom an Image at the same time.

Retriving the rotation angle with RotationGesture. Retriving the magnification value with MagnificationGesture.
You can use simultaneousGesture to perform both of the above Gesture methods at the same time.
As shown in the image, you can use two fingers to rotate and scale at the same time.

You can apply rotation angle with rotationEffect and magnification with scaleEffect.

This time, I used lastAngle and lastMagnify to add rotation and expansion to it's condition.
Comment out them if you want the image to return to its initial state with each gesture.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView: View {
    @State private var magnify: CGFloat = 1
    @State private var lastMagnify: CGFloat = 1
    @State private var angle: Angle = .degrees(.zero)
    @State private var lastAngle: Angle = .degrees(.zero)
    
    var body: some View {
        VStack () {
            ZStack () {
                Image("ice_1")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .scaleEffect(self.magnify)
                    .rotationEffect(self.angle)
                    .gesture(RotationGesture()
                        .onChanged{ angle in
                            self.angle = angle + self.lastAngle
                        }
                        .onEnded { angle in
                            self.lastAngle = self.angle
                        }
                    )
                    .simultaneousGesture(MagnificationGesture()
                        .onChanged{ v in
                            let delta = v / self.lastMagnify
                            self.lastMagnify = v
                            self.magnify *= delta
                        }
                        .onEnded{ v in
                            self.lastMagnify = 1
                        }
                    )
                    .clipShape(Circle())
                    .overlay(
                        Circle().stroke(LinearGradient(gradient: Gradient(colors: [.yellow, .red, .purple]), startPoint: .bottomLeading, endPoint: .topTrailing), lineWidth: 5))
            }
        }
    }
}

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アドレス保存アプリのスクリーンショット