在Swiftui中没有简单的方法来放大图像吗? [英] Isn't there an easy way to pinch to zoom in an image in Swiftui?

查看:320
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆