为什么SwiftUI放大手势会跳动?

时间:2020-10-06 21:45:11

标签: ios swift swiftui

我测试了MagnificationGesture的工作方式,并提供了以下代码(有些杂乱无章!)

struct ImageOpacityView: View {
    @Binding var opacity: Double
    @Binding var image: Image
    
    @State var magScale: CGFloat = 1

    var magnificationGesture: some Gesture {
        MagnificationGesture().onChanged { gesture in
            self.magScale = gesture
        }
    }
    
    var body: some View {
        
        self.image
            .resizable()
            .aspectRatio(contentMode: .fit)
            .opacity(opacity / 100)
            .gesture(self.magnificationGesture)
            .scaleEffect(self.magScale)
            .frame(width: 200, height: 200)
    }
}

struct ContentView: View {
    @State var opacity: Double = 50
    @State var image = Image(systemName: "photo.fill")
    
    var body: some View {
        ImageOpacityView(opacity: self.$opacity, image: self.$image)
    }
}

这只是我正在寻找的简单缩放效果,可以与其他功能(例如,不透明度更改和拖动手势)结合使用,到目前为止,我在此处发现的所有示例在捏捏发生时都不平滑。 ..

我很高兴有人能引导我正确的方向...

1 个答案:

答案 0 :(得分:0)

此代码在理论上应该起作用!但是经过很多努力之后,我发现手势跳动的原因是因为我对图像执行的操作顺序。将.gesture(self.magnificationGesture)一直向下移动确实解决了跳跃问题!

struct ImageOpacityView: View {
    @Binding var opacity: Double
    @Binding var image: Image
    
    @State var magScale: CGFloat = 1

    var magnificationGesture: some Gesture {
        MagnificationGesture().onChanged { gesture in
            self.magScale = gesture
        }
    }
    
    var body: some View {
        
        self.image
            .resizable()
            .aspectRatio(contentMode: .fit)
            .opacity(opacity / 100)
            .scaleEffect(self.magScale)
            .frame(width: 200, height: 200)
            .gesture(self.magnificationGesture)
    }
}

struct ContentView: View {
    @State var opacity: Double = 50
    @State var image = Image(systemName: "photo.fill")
    
    var body: some View {
        ImageOpacityView(opacity: self.$opacity, image: self.$image)
    }
}