Filip Filip - 4 months ago 18
Objective-C Question

Create rectangle from UIImage

I was wondering if its possible to create a rectangle from the image below to eliminate the weird corners:

Rectangle

Input Image:

<UIImage>, {1334, 955}


This is what I have so far:

int croppingNumber = 50;

CGRect croprect = CGRectMake(croppingNumber, imageToCrop.size.height - croppingNumber, imageToCrop.size.width - croppingNumber, imageToCrop.size.height - croppingNumber);

// Draw new image in current graphics context
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], croprect);

// Create new cropped UIImage
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

NSLog(@"cropped is: %@",croppedImage);

CGImageRelease(imageRef);


Result from code above:

cropped is: <UIImage:>, {1338, 50}

Answer

You need to allow for enough to space to cover the right & bottom, so multiply your croppingNumber by 2. Otherwise, the 50 point shift to the right / down will just push your square into the bottom right most corner.

// Create rectangle from middle of current image
CGFloat croppingNumber = 50.0;
CGRect cropRect = CGRectMake(croppingNumber, croppingNumber, imageToCrop.size.width - (croppingNumber * 2), imageToCrop.size.height - (croppingNumber * 2));

// Draw new image in current graphics context
CGImageRef imageRef = CGImageCreateWithImageInRect(imageToCrop.CGImage, cropRect);

// Create new cropped UIImage
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

NSLog(@"cropped is: %@",croppedImage);

CGImageRelease(imageRef);
Comments