Flexsin Flex Flexsin Flex - 1 year ago 187
Objective-C Question

How to crop center part of large image in iOS?

When a image is cropped from the center then crop image will take the aspect ratio of source image,But According to my requirement, aspect ratio will be change with new crop size.

I want to get exact center part of image with new aspect ratio.For example a large image is of size (320*480) then I want to crop center part of image of size (100,100) and aspect ratio will also be 100*100 ,No outer white or black part is required and image quality will be high.

Cropping function :

- (UIImage *)cropImage:(UIImage*)image andFrame:(CGRect)rect {

//Note : rec is nothing but the image frame which u want to crop exactly.

rect = CGRectMake(rect.origin.x*image.scale,

CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *result = [UIImage imageWithCGImage:imageRef
return result;

Please help me.

Answer Source

This might run

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
    // not equivalent to image.size (which depends on the imageOrientation)!
    double refWidth = CGImageGetWidth(image.CGImage);
    double refHeight = CGImageGetHeight(image.CGImage);

    double x = (refWidth - size.width) / 2.0;
    double y = (refHeight - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:self.imageOrientation];

    return cropped;