如何确定用户在 UIImage 上点击了哪个像素 (x, y)?

Vah*_*hid 1 image swift

我有一个UIImageView. 我添加一个图像并点击图像的某些位置。

有没有办法确定点击图像的像素(x,y)是多少?

考试:

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

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

Ger*_*eon 5

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

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)")
}
Run Code Online (Sandbox Code Playgroud)