0

I am trying to create a simple cropping app. I have a view overlayed on a UIImage and I want to crop a new image out of only the part of the UIImage where the view is overlayed. I used the code

CGRect cropRect = _cropView.frame;
UIImage *cropImage = [UIImage imageWithData:imageData];
CGImageRef cropped = CGImageCreateWithImageInRect([cropImage CGImage], cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:cropped];
self.imageView.image = croppedImage;

but it resulted in an unexpected image that seemed very zoomed in and not what I wanted. How can I crop a new image from the image behind the view?

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
cvrattos
  • 51
  • 1
  • 4

2 Answers2

0

A CGImage deals with pixels, not "points" (the abstract measurement unit of UIKit). When the crop view's contentScaleFactor is larger than 1, its pixel dimensions will be larger than its point dimensions. So, to get a crop rect that corresponds to the pixels, you need to multiply all of the coordinates and dimensions of the view's frame by its contentScaleFactor.

CGRect cropRect = _cropView.frame;
cropRect.origin.x *= _cropView.contentScaleFactor;
cropRect.origin.y *= _cropView.contentScaleFactor;
cropRect.size.width *= _cropView.contentScaleFactor;
cropRect.size.height *= _cropView.contentScaleFactor;
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • I tried this and it did not fix the problem. The image is still way too zoomed in and also rotated 90 degrees counterclockwise – cvrattos Jul 13 '18 at 16:56
0

May be this help you,

// Create new image context
CGSize size = _cropView.frame.size;

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

// Create rect for image
CGRect rect = _cropView.frame;

// Draw the image into the rect
[existingImage drawInRect:rect];

// Saving the image, ending image context
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
Vicky_Vignesh
  • 584
  • 2
  • 14
  • Thank you for your response but this ended up not working either. I am still very confused by my output – cvrattos Jul 13 '18 at 17:02