CGImageCreateWithImageInRect

375 Views Asked by At

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?

2

There are 2 best solutions below

1
Ken Thomases On

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;
1
Vicky_Vignesh On

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();