swift - 如何确定在 UIImage 而不是 UIImageView 上点击的 (x, y) 用户的位置?

标签 swift image

UIImage 将在运行时添加到 UIImageView,我想确定用户点击图像的位置。

有什么方法可以确定点击图像的像素 (x,y) 是多少?

考试:

如果我有 apple.png 图像大小为 x:1000, y:1000 并且我点击它的正中心,它应该返回 x : 500, y: 500

我需要真实图像 (UIImageView.image) 上的点击点像素,而不是 UIImageView

最佳答案

是的,通过将 UITapGestureRecognizer 添加到 ImageView ,从中获取点击位置并将点击坐标转换为图像坐标:

let img = UIImage(named: "whatever")

// add a tap recognizer to the image view
let tap = UITapGestureRecognizer(target: self, 
             action: #selector(self.tapGesture(_:)))
imgView.addGestureRecognizer(tap)
imgView.isUserInteractionEnabled = true
imgView.image = img
imgView.contentMode = .scaledAspectFit

func convertTapToImg(_ point: CGPoint) -> CGPoint? {
    let xRatio = imgView.frame.width / img.size.width
    let yRatio = imgView.frame.height / img.size.height
    let ratio = min(xRatio, yRatio)

    let imgWidth = img.size.width * ratio
    let imgHeight = img.size.height * ratio

    var tap = point
    var borderWidth: CGFloat = 0
    var borderHeight: CGFloat = 0
    // detect border
    if ratio == yRatio {
        // border is left and right
        borderWidth = (imgView.frame.size.width - imgWidth) / 2
        if point.x < borderWidth || point.x > borderWidth + imgWidth {
            return nil
        }
        tap.x -= borderWidth
    } else {
        // border is top and bottom
        borderHeight = (imgView.frame.size.height - imgHeight) / 2
        if point.y < borderHeight || point.y > borderHeight + imgHeight {
            return nil
        }
        tap.y -= borderHeight
    }

    let xScale = tap.x / (imgView.frame.width - 2 * borderWidth)
    let yScale = tap.y / (imgView.frame.height - 2 * borderHeight)
    let pixelX = img.size.width * xScale
    let pixelY = img.size.height * yScale
    return CGPoint(x: pixelX, y: pixelY)
}

@objc func tapGesture(_ gesture: UITapGestureRecognizer) {
    let point = gesture.location(in: imgView)
    let imgPoint = convertTapToImg(point)
    print("tap: \(point) -> img \(imgPoint)")
}

关于swift - 如何确定在 UIImage 而不是 UIImageView 上点击的 (x, y) 用户的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48486868/

相关文章:

swift - 为什么我的播放器通过倾斜屏幕 (SWIFT 3) 不移动 (CMMotionManager)?

ios - 什么是 Flurry 的正确桥接头?

Java:读取图像并显示为 ImageIcon

html - CSS 中的地址应该是什么(用于链接和图像)

ios - Storyboard选项在 Xcode v7.0 中对 iPad 不可见

swift - 删除相互依赖的对象时了解核心数据

android - 使用异步任务下载图像并在图库中显示

javascript - Canvas :点击图像

html - 嵌套在 <p> 标签中时如何更改图像大小

ios - Swift 可选链