获取ImageView的触摸点所对应的UIImage的坐标
获取ImageView的触摸点所对应的UIImage的坐标
功能描述
在imageview上触摸图片,求对应UIImage的触摸点。
实现前分析
从imageview上获取触摸点是比较容易的事情,但是由于imageview的大小、比例的关系,获得的触摸点不能直接被认为是UIImage上的点。在这里将会根据大小、比例对触摸点进行操作,以期望得到对应的UIImage的点。
(蓝色区域为imageview的区域,当我触摸红点时可以轻易的获取该点在imageview上的坐标(71.666656,120.000000),然而这并不代表该点在UIImage的坐标也是如此)
注意事项
在实践过程中发现如果view出现了旋转的时候,这个时候坐标系会出现旋转,圆心在图片左上角,而view的大小会出现变化,这个时候依照view的大小比例来进行缩放结果将会出现问题(如图所示)。
代码
- (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; }
求打赏
本文来自博客园,作者:MrYu4,转载请注明原文链接:https://www.cnblogs.com/MrYU4/p/15778879.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了