讓一個(gè)swiftUI View 擁有多種手勢(shì)操作

//
//  ContentView.swift
//  PencilDraw
//
//  Created by wangxuncai on 2021/12/5.
//

import SwiftUI
struct GestureView<Content: View>: View {
    let content: Content
    @State private var currentAmount: CGFloat = 0
    @State private var finalAmount: CGFloat = 1
    @State private var currentRotationAmount: Angle = .degrees(0)
    @State private var finalRotationAmount: Angle = .degrees(0)
    @State private var offset:CGSize = CGSize.zero
    @State private var finalOffset:CGSize = CGSize.zero
    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
    
    var body: some View {
        let rotation =  RotationGesture()
            .onChanged { angle in
                currentRotationAmount = angle
            }
            .onEnded { angle in
                finalRotationAmount += self.currentRotationAmount
                currentRotationAmount = .degrees(0)
            }
        let magnification = MagnificationGesture()
            .onChanged { amount in
                currentAmount = amount - 1
            }
            .onEnded { amount in
                finalAmount += self.currentAmount
                currentAmount = 0
            }
        let moveGesture = DragGesture().onChanged { value in
            offset = value.translation
        }.onEnded { value in
            finalOffset.width += self.offset.width
            finalOffset.height += self.offset.height
            offset = CGSize.zero
        }
        
        
        
        let combineGesture = rotation.simultaneously(with: magnification)
        let finalGesture = combineGesture.simultaneously(with: moveGesture)
        content
            .scaleEffect(finalAmount + currentAmount)
            .rotationEffect(currentRotationAmount + finalRotationAmount)
            .offset(x: offset.width + finalOffset.width, y: offset.height + finalOffset.height)
            .gesture(
                finalGesture
            )
           
           
    }
}

//使用方法
struct ContentView: View {
   
    @State var image:UIImage = UIImage(named: "1")!
    var body: some View {
         
        GestureView{
    
            CanvasBoard(image: $image)//這個(gè)被包裹的 CanvasBoard 就有了手勢(shì)操作
        }
    }
    
}

蘋(píng)果應(yīng)用商店|搜|王勛才|有我全部作品
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容