Getting the right coordinates of the visible part of a UIImage inside of UIScrollView

本秂侑毒 提交于 2019-12-12 01:09:25

问题


I have a UIImage which is inside a UIScrollView so I can zoom-in and zoom-out, crop, move around, etc.

How do I get the coordinates of the visible part of the UIImage inside the UIScrollView. I want to crop the image in it's native resolution (using GPUIImage) but I need to x, y, width and height for the rectangle.


回答1:


I use a scrollview to enable zoom of a UIImage. A cropping button presents an overlaid resizable cropping view. The following is the code I use to ensure the user defined crop box in the UIScrollView gets added with the correct coordinates to the UIImageView (can then use to crop image).

To find the x and y coordinates use the scrollview contentOffset multiplied by inverse of zoomscale:

float origX = 0;
float origY = 0;
float widthCropper = 0;
float heightCropper = 0;


if (_scrollView.contentOffset.x > 0){
    origX = (_scrollView.contentOffset.x) * (1/_scrollView.zoomScale);
}
if (_scrollView.contentOffset.y > 0){
    origY = (_scrollView.contentOffset.y) * (1/_scrollView.zoomScale);
}

If you need to create a properly sized cropping box for what is displayed in the scrollview you will need to adjust the width and the height for any zoom factor:

widthCropper = (_scrollView.frame.size.width * (1/_scrollView.zoomScale));
heightCropper = (_scrollView.frame.size.height * (1/_scrollView.zoomScale));

and to add this properly sized rectangle as a cropping view to the UIImageView:

CGRect cropRect = CGRectMake((origX + (SIDE_MARGIN/2)), (origY + (SIDE_MARGIN / 2)), (widthCropper - SIDE_MARGIN), (heightCropper  - SIDE_MARGIN));
_cropView = [[UIView alloc]initWithFrame:cropRect];
[_cropView setBackgroundColor:[UIColor grayColor]];
[_cropView setAlpha:0.7];
[_imageView addSubview:_cropView];
[_imageView setCropView:_cropView];


来源:https://stackoverflow.com/questions/16515103/getting-the-right-coordinates-of-the-visible-part-of-a-uiimage-inside-of-uiscrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!