获取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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值