Gobinath Ed
Gobinath Ed

Reputation: 229

How can crop an image of any size to a certain dimension?

My requirement is When I handle an image of any dimension that image should be cropped automatically to a dimension of 320x240 without any stretch. How can I write a crop method for this functionality? I mean I've list of images with various dimensions if i pick an image from this list it will be automatically converted to the dimension 320x 240. How can I achieve it. Please advise me.

Now I'm using the following coding : http://www.abdus.me/ios-programming-tips/resize-image-in-ios/

But the quality of the resultant image is not good it gets blurred. Could you please tell me how can I overcome this issue.

Upvotes: 2

Views: 685

Answers (1)

Kumar KL
Kumar KL

Reputation: 15335

For crop - Portion of image :

- (UIImage*) getSubImageFrom: (UIImage*) img WithRect: (CGRect) rect {

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // translated rectangle for drawing sub image
    CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, img.size.width, img.size.height);

    // clip to the bounds of the image context
    // not strictly necessary as it will get clipped anyway?
    CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));

    // draw image
    [img drawInRect:drawRect];

    // grab image
    UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return subImage;
}

For Resize -

Put the UIImageView's frame into 320x240 and then imageView.contentMode = UIViewContentModeScaleAspectFit;

Upvotes: 2

Related Questions