How to crop a center square in a UIImage?
crop, ios, uiimage
Solution
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);
}
Problem
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; } ```