Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS get Visible portion of Image for an UIImageView

I'm trying get the visible portion of UIImage from an UIImageView. UIImageView takes the entire screen. Pinch & Pan gesture is added to UIImageView. So, User can pan/zoom the imageview. After pan/zoom I want to crop only the visible part of the image view. I've tried a number of methods. But it returns me wrong part of image.

Thanks In advance.

like image 940
Walid Hossain Avatar asked Dec 19 '25 11:12

Walid Hossain


2 Answers

Include QuartzCore framework to your project and implement this method for getting visible part of image from your image view: (one note: i mean that you are using ARC in your project)

#import <QuartzCore/QuartzCore.h>

- (UIImage*)imageFromImageView:(UIImageView*)imageView
{
    UIGraphicsBeginImageContext(imageView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextRotateCTM(context, 2*M_PI);

    [imageView.layer renderInContext:context];
    UIImage *image =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
like image 132
ZGl6YXNt Avatar answered Dec 22 '25 00:12

ZGl6YXNt


Thank you all. I've figured out the solution. Here is the code that I used to get the visible portion of the image. (Keep it in your mind that the image was not fully visible when zoomed or pan due to it was taking entire screen)

  - (UIImage *)cropVisiblePortionOfImageView:(UIImageView *)imageView {

  CGFloat zoomScaleX=imageView.frame.size.width/initialWidth;
  CGFloat zoomScaleY=imageView.frame.size.height/initialHeight;
  CGSize zoomedSize=CGSizeMake(initialWidth*zoomScaleX,initialHeight*zoomScaleY);

  UIGraphicsBeginImageContext(zoomedSize);
  [imageView.image drawInRect:CGRectMake(0, 0, zoomedSize.width, zoomedSize.height)];
  UIImage *zoomedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  UIGraphicsBeginImageContext(CGSizeMake(initialWidth, initialHeight));
  [zoomedImage drawAtPoint:CGPointMake(imageView.frame.origin.x, imageView.frame.origin.y)];
  UIImage *cropedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return cropedImage;
}
like image 23
Walid Hossain Avatar answered Dec 22 '25 01:12

Walid Hossain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!