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/