如何确定用户在UIImage上点击了哪个像素(x,y)? [英] How to determine what pixel (x, y) user tapped on a UIImage?
问题描述
我有一个UIImageView
.我添加一张图片,然后点击图片的某些位置.
I have a UIImageView
. I add an image and tap on some where of image.
有什么方法可以确定点击的图像的像素(x,y)?
Is there any way to determine what is the pixel (x,y) of tapped image?
考试:
如果我的apple.png
的图像尺寸为x:1000, y:1000
,并且我恰好点击了它的中心,它应该返回x: 500, y: 500
If I have apple.png
by image size of x:1000, y:1000
and I tap on exactly center of it, it should return x: 500, y: 500
我需要在真实图像(UIImageView.image
)上点击点像素,而不是UIImageView
I need tapped point pixels on real image (UIImageView.image
) not UIImageView
推荐答案
是的,通过在图像视图中添加UITapGestureRecognizer
,从中获取拍子位置并将拍子坐标转换为图像坐标:
Yes, by adding a UITapGestureRecognizer
to the image view, getting the tap position from that and converting the tap coordinates to the image coordinates:
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)")
}
这篇关于如何确定用户在UIImage上点击了哪个像素(x,y)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!