美文网首页
让一个swiftUI View 拥有多种手势操作

让一个swiftUI View 拥有多种手势操作

作者: 王勋才 | 来源:发表于2021-12-05 20:18 被阅读0次
//
//  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)//这个被包裹的 CanvasBoard 就有了手势操作
        }
    }
    
}

苹果应用商店|搜|王勋才|有我全部作品

相关文章

网友评论

      本文标题:让一个swiftUI View 拥有多种手势操作

      本文链接:https://www.haomeiwen.com/subject/gyrwxrtx.html