根据UIImageView中的图像查找触摸位置 [英] Finding touch location according to image in UIImageView

查看:115
本文介绍了根据UIImageView中的图像查找触摸位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UIImageView中有一个图像,UIImageView的内容模式设置为UIViewContentModeScaleAspectFit。那么如何根据图像找到触摸位置。请记住,我的图像大小分辨率很大,如2000 x 3000。

I have an image in UIImageView and the content mode of UIImageView is set be UIViewContentModeScaleAspectFit. so how can I find the touch location according to image. Keep it in mind , my image size has large resolution like 2000 x 3000.

推荐答案

试试这段代码。我没有测试它,所以可能犯了错误。我希望这些评论能够帮助你找到正确的解决方案。

Try this code. I did not test it so mistakes might have been made. I hope the comments will help you enough to find the correct solution.

- (CGPoint)point:(CGPoint)point onImageWithSize:(CGSize)imageSize inImageView:(UIImageView *)view contentMode:(UIViewContentMode)mode
{
    // find the relative image position on the view
    CGPoint imageRelativeOrigin = CGPointZero;
    CGSize imageRelativeSize = view.frame.size;

    if(mode == UIViewContentModeScaleAspectFit)
    {
        // we expect one of the origin coordinates has a positive offset
        // compare the ratio
        if(imageSize.width/imageSize.height > view.frame.size.width/view.frame.size.height)
        {
            // in this case the image width is the same as the view width but height is smaller
            imageRelativeSize = CGSizeMake(view.frame.size.width, view.frame.size.width*(imageSize.height/imageSize.width));
            CGFloat verticalOffset = (view.frame.size.height-imageRelativeSize.height)*.5f; // this is the visible image offset
            imageRelativeOrigin = CGPointMake(.0f, verticalOffset);
        }
        else
        {
            // in this case the image height is the same as the view height but widh is smaller
            imageRelativeSize = CGSizeMake(view.frame.size.height*(imageSize.width/imageSize.height), view.frame.size.height);
            CGFloat horizontalOffset = (view.frame.size.width-imageRelativeSize.width)*.5f; // this is the visible image offset
            imageRelativeOrigin = CGPointMake(horizontalOffset, .0f);
        }
    }
    else
    {
        // TODO: add other content modes
    }

    CGPoint relativeImagePoint = CGPointMake(point.x-imageRelativeOrigin.x, point.y-imageRelativeOrigin.y); // note these can now be off the image bounds
    // resize to image coordinate system
    CGPoint actualImagePoint = CGPointMake(relativeImagePoint.x*(imageSize.width/imageRelativeSize.width),
                                           relativeImagePoint.y*(imageSize.height/imageRelativeSize.height));
    return actualImagePoint;
}

这篇关于根据UIImageView中的图像查找触摸位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆