获取ImageView的触摸点所对应的UIImage的坐标

获取ImageView的触摸点所对应的UIImage的坐标

功能描述

在imageview上触摸图片,求对应UIImage的触摸点。

实现前分析

从imageview上获取触摸点是比较容易的事情,但是由于imageview的大小、比例的关系,获得的触摸点不能直接被认为是UIImage上的点。在这里将会根据大小、比例对触摸点进行操作,以期望得到对应的UIImage的点。

pic1

(蓝色区域为imageview的区域,当我触摸红点时可以轻易的获取该点在imageview上的坐标(71.666656,120.000000),然而这并不代表该点在UIImage的坐标也是如此)

注意事项

在实践过程中发现如果view出现了旋转的时候,这个时候坐标系会出现旋转,圆心在图片左上角,而view的大小会出现变化,这个时候依照view的大小比例来进行缩放结果将会出现问题(如图所示)。

pic2

代码

- (CGPoint)getTouchPointOnImageWithImageView:(UIImageView *)imageView
touchPoint:(CGPoint)ivTouchPoint {
//only support UIViewContentModeScaleAspectFit
if (!imageView ||
!imageView.image ||
imageView.contentMode != UIViewContentModeScaleAspectFit) {
return CGPointZero;
}
//避免被旋转后的原imageview给干扰
UIImageView *tempIv = [[UIImageView alloc]initWithImage:imageView.image];
tempIv.transform = imageView.transform;
tempIv.bounds = imageView.bounds;
//旋转回去
arg = atan(tempIv.transform.b / tempIv.transform.a);
tempIv.transform = CGAffineTransformRotate(tempIv.transform, -arg);
CGPoint imgTouchPoint = ivTouchPoint;
BOOL widthHasEmpty = tempIv.image.size.height * tempIv.frame.size.width > tempIv.image.size.width * tempIv.frame.size.height;
BOOL heightHasEmpty = tempIv.image.size.height * tempIv.frame.size.width < tempIv.image.size.width * tempIv.frame.size.height;
CGFloat H, h;
if (heightHasEmpty) {
H = tempIv.image.size.height * tempIv.frame.size.width / tempIv.image.size.width;
h = (tempIv.frame.size.height - H) / 2;
} else {
H = tempIv.frame.size.height;
h = 0;
}
if (heightHasEmpty) {
imgTouchPoint.y -= h;
}
CGFloat W,w;
if (widthHasEmpty) {
W = tempIv.image.size.width * tempIv.frame.size.height / tempIv.image.size.height;
w = (tempIv.frame.size.width - W) / 2;
} else {
W = tempIv.frame.size.width;
w = 0;
}
if (widthHasEmpty) {
imgTouchPoint.x -= w;
}
if (!CGRectContainsPoint(CGRectMake(0, 0, tempIv.image.size.width, tempIv.image.size.height), imgTouchPoint)) {
NSLog(@"touch point is out of range");
return CGPointZero;
}
return imgTouchPoint;
}

求打赏

pic3

posted @   MrYu4  阅读(46)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示