在 Swiftui 中没有一种简单的方法可以通过捏来放大图像吗? [英] Isn't there an easy way to pinch to zoom in an image in Swiftui?
问题描述
我希望能够在 SwiftUI 中调整大小和移动图像(就像地图一样),同时捏合缩放和拖动它.
I want to be able to resize and move an image in SwiftUI (like if it were a map) with pinch to zoom and drag it around.
我使用 UIKit 将图像嵌入到 UIScrollView
中并处理它,但我不知道如何在 SwiftUI 中执行此操作.我尝试使用 MagnificationGesture
但我无法让它顺利工作.
With UIKit I embedded the image into a UIScrollView
and it took care of it, but I don't know how to do it in SwiftUI.
I tried using MagnificationGesture
but I cannot get it to work smoothly.
我一直在寻找这个,有没有人知道是否有更简单的方法?
I've been searching about this for a while, does anyone know if there's an easier way?
推荐答案
SwiftUI API 在这里非常没有帮助:onChanged 给出了相对于当前缩放手势的开始的数字,并且在回调中没有明显的方法来获取初始值.还有一个 onEnded 回调,但很容易错过/忘记.
The SwiftUI API is pretty unhelpful here: the onChanged gives number relative to start of current zoom gesture and no obvious way within a callback to get the initial value. And there is an onEnded callback but easy to miss/forget.
解决方法,添加:
@State var lastScaleValue: CGFloat = 1.0
然后在回调中:
.gesture(MagnificationGesture().onChanged { val in
let delta = val / self.lastScaleValue
self.lastScaleValue = val
let newScale = self.scale * delta
//... anything else e.g. clamping the newScale
}.onEnded { val in
// without this the next gesture will be broken
self.lastScaleValue = 1.0
}
其中 newScale 是您自己的比例跟踪(可能是状态或绑定).如果你直接设置你的比例,它会变得一团糟,因为在每个刻度上,数量将相对于之前的数量.
where newScale is your own tracking of scale (perhaps state or a binding). If you set your scale directly it will get messed up as on each tick the amount will be relative to previous amount.
这篇关于在 Swiftui 中没有一种简单的方法可以通过捏来放大图像吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!