Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping center square of UIImage

Tags:

ios

image

uiimage

So here's where I've made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn't translate to portrait mode as expected. I'll post my code and logs just for reference.

Code:

CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight); CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect); image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation]; 

Portrait results (not square):

original image size: {1536, 2048}, with orientation: 3 squareRect: {{0, 256}, {1536, 1536}} new image size: {1280, 1536}, with orientation: 3 <--- not expected 

Landscape results (square):

original image size: {2048, 1536}, with orientation: 1 squareRect: {{256, 0}, {1536, 1536}} new image size: {1536, 1536}, with orientation: 1 

Is this a bug within CGImageCreateWithImageInRect() or am I missing something here?

like image 813
Uxonith Avatar asked Jan 07 '13 21:01

Uxonith


1 Answers

I think here would be the perfect solution!
It is NOT good idea to crop image basis on the toSize's size. It will look weird when the image resolution (size) is very large.
Following code will crop the image as per the toSize's ratio.
Improved from @BlackRider's answer.

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size {     double newCropWidth, newCropHeight;      //=== To crop more efficently =====//     if(image.size.width < image.size.height){          if (image.size.width < size.width) {                  newCropWidth = size.width;           }           else {                  newCropWidth = image.size.width;           }           newCropHeight = (newCropWidth * size.height)/size.width;     } else {           if (image.size.height < size.height) {                 newCropHeight = size.height;           }           else {                 newCropHeight = image.size.height;           }           newCropWidth = (newCropHeight * size.width)/size.height;     }     //==============================//      double x = image.size.width/2.0 - newCropWidth/2.0;     double y = image.size.height/2.0 - newCropHeight/2.0;      CGRect cropRect = CGRectMake(x, y, newCropWidth, newCropHeight);     CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);      UIImage *cropped = [UIImage imageWithCGImage:imageRef];     CGImageRelease(imageRef);      return cropped; } 
like image 190
Nirav Dangi Avatar answered Oct 11 '22 10:10

Nirav Dangi