MagnificationGesture in SwiftUI

108 阅读1分钟

MagnificationGesture可用于检测手势缩放事件,例如在地图中使用的缩放功能。

MagnificationGesture使用很简单,他有两个方法,一个是onChanged方法,一个是onEnded方法。onChanged的方法可以实时输出被缩放的对象的缩放值, 这个值是大于0的。

下面看一个例子:

@State var currentValue: CGFloat = 0
@State var lastValue: CGFloat = 0

Text("Hello, World!")
                    .foregroundColor(.white)
                    .font(.largeTitle)
                    .padding(40)
                    .background(Color.orange)
                    .cornerRadius(10)
 .scaleEffect(1 + currentValue + lastValue)
                    .gesture(
                        MagnificationGesture()
                            .onChanged { value in
                                currentValue = value - 1
                            }
                            .onEnded { value in
                                lastValue += currentValue
                                currentValue = 0
                            } 
                    )

以上代码就可以使Text文本就行缩放,并且保留了最后一次缩放的大小。不会在下次缩放时带来跳跃感。

ezgif.com-video-to-gif.gif

再来看一个实际的例子,在很多app中。图片部分是可以被单独进行缩放查看的,当我们解释缩放时,图片会回到原来大小。我们就用这个场景来使用我们刚学到的缩放手势。

VStack {
            HStack {
                Circle()
                    .frame(width: 35, height: 35)
                Text("SwiftUI tutorial")
                Spacer()
                Image(systemName: "ellipsis")
            }
            .padding(.horizontal)

            Rectangle()
                .fill()
                .frame(height: 300)
                .scaleEffect(1 + currentValue)
                .gesture(
                    MagnificationGesture()
                        .onChanged { value in
                            currentValue = value
                        }
                        .onEnded { value in
                            withAnimation(.spring()) {
                                currentValue = 0
                            }
                        }
                )
            HStack {
                Image(systemName: "heart.fill")
                Image(systemName: "text.bubble.fill")
                Spacer()
            }
            .font(.headline)
            .padding(.horizontal)
            Text("This is my post first phone")
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.horizontal)
        }

ezgif.com-video-to-gif (1).gif

大家有什么看法呢?欢迎留言讨论。
公众号:RobotPBQ