在 UIScrollView 上裁剪当前触摸点并将其显示在 UIView 中

Crop the current touch point on a UIScrollView and display it in a UIView

提问人:Gavin Wright 提问时间:8/25/2023 最后编辑:Gavin Wright 更新时间:8/25/2023 访问量:36

问:

我正在研究绘图功能。我需要用户能够看到在他们的手指下绘制的内容。这张照片位于 .我基本上只想裁剪当前指针位置周围的区域,并将其显示在屏幕顶部的单独视图中。以下 GIF 来自 Android,显示了我想要实现的行为(请参阅顶部的圆形区域,我称之为“缩放器”窗口):UIScrollView

Here's the effect I want to achieve

我在 iOS 中实现此功能时遇到问题。以下代码是我尝试将此缩放器窗口实现为矩形的尝试:

UIGraphicsBeginImageContextWithOptions(CGSize(width: zoomerWindowWidth, height: zoomerWindowWidth), false, 0)
let cropRect = CGRect(
        x: -(lastPointTouched.x - zoomerWindowWidth / 2),
        y: -(lastPointTouched.y + zoomerWindowWidth / 2),
        width: view.bounds.size.width,
        height: view.bounds.size.height
)

mainScrollView.drawHierarchy(in: cropRect, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
zoomerImageView.image = image

这几乎有效,但当前触摸点不会在缩放器窗口中保持居中。当放大或缩小时,窗口会更加不对齐。我乘以比例因子的尝试都失败了。UIScrollView

以下是它目前的样子:

What it currently looks like

TLDR:我需要小窗口保持在当前触摸位置的中心。谁能帮忙?

以下是完整的代码库: https://github.com/gavingt/ios_draw_zoom .请特别看这里

iOS Swift UIscrollView UIKit 、裁剪

评论


答:

0赞 Gavin Wright 8/25/2023 #1

一位友好的 Redditor 找到了解决方案:

let lastPointTouched = view.convert(self.lastPointTouched, from: drawingImageView)
let cropRect = CGRect(
        x: -(lastPointTouched.x - zoomerWindowWidth / 2),
        y: -(lastPointTouched.y - zoomerWindowWidth/2 ),
        width: view.bounds.size.width,
        height: view.bounds.size.height
)

您还可以查看最新的 Github 提交以获取工作版本。