【问题标题】:How to determine location of (x, y) user tapped on a UIImage not UIImageView?如何确定(x,y)用户在 UIImage 而不是 UIImageView 上点击的位置?
【发布时间】:2018-01-28 13:29:26
【问题描述】:

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

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

考试:

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

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

【问题讨论】:

  • 你在使用.scaleAspectFit吗?如果是这样,您需要具备三样东西:(1) 点击的point 位置,(2) 显示图像的实际CGRect - 注意,not图像视图的CGRect,最后是(3)在两者之间转换的计算/公式。我有一个UIImage 扩展名,应该可以帮助你解决第二个问题。它返回图像视图渲染图像的“比例因子”,无论它是向上还是向下调整大小。我只是不确定它是否会与其他 .contentModes 正常运行。
  • 是的@dfd,我使用scaleAspectFit。我已经有了点击位置的点,但它基于屏幕的 x,y。
  • 再想一想,我最多只能让你走到一半。我的扩展程序将为您提供图像的 缩放点 位置,但我认为您想要一些不同的东西。为此,我相信您需要研究 CGImage 或 Core Graphics。快速搜索产生了一个受保护的问题(从 2009 年开始,在 Obj-C 中),这可能会给你一个开始:stackoverflow.com/questions/448125/…

标签: swift image


【解决方案1】:

是的,通过将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)")
}

【讨论】:

  • 我认为 OP 想要的是 UIImage.sizepixel 位置,而不是 UIImageViewpoint 值。跨度>
  • 谢谢@Gereon,但我想要UIImage 上点击点的像素位置。不是UIImageView
  • 当你有a)点击位置,b)UIImage的大小,c)UIImageView的框架和d)屏幕的比例因子时,计算不是很简单吗?
  • @Gereon,如果你知道如何计算,请告诉我。
  • 更新了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
相关资源
最近更新 更多