Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop a center square in a UIImage?

Tags:

ios

uiimage

crop

Sorry about this question, but I searched a lot of threads here in S.O. and I found nothing.

The question is: how to crop a center square in a UIImage?

I tried the code bellow but without success. The cropping happens, but in the upper-left corner.

-(UIImage*)imageCrop:(UIImage*)original
{
    UIImage *ret = nil;

    // This calculates the crop area.

    float originalWidth  = original.size.width;
    float originalHeight = original.size.height;

    float edge = fminf(originalWidth, originalHeight);

    float posX = (originalWidth   - edge) / 2.0f;
    float posY = (originalHeight  - edge) / 2.0f;


    CGRect cropSquare = CGRectMake(posX, posY,
                                   edge, edge);


    // This performs the image cropping.

    CGImageRef imageRef = CGImageCreateWithImageInRect([original CGImage], cropSquare);

    ret = [UIImage imageWithCGImage:imageRef
                              scale:original.scale
                        orientation:original.imageOrientation];

    CGImageRelease(imageRef);

    return ret;
}
like image 861
Danilo Gomes Avatar asked Jun 14 '12 17:06

Danilo Gomes


1 Answers

Adding more information, I'm using this 'crop' after a photo capture.

After some tests, I found something that worked.

// If orientation indicates a change to portrait.
if(original.imageOrientation == UIImageOrientationLeft ||
   original.imageOrientation == UIImageOrientationRight)
{
    cropSquare = CGRectMake(posY, posX,
                            edge, edge);

}
else
{
    cropSquare = CGRectMake(posX, posY,
                            edge, edge);
}
like image 197
Danilo Gomes Avatar answered Nov 10 '22 18:11

Danilo Gomes