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;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With