2014/04/14

Cropping a UIImage

I just wanted to crop an image (a UIImage object). I had done this and I thought it was easy, but I found soon it was wrong.
This code below is one way to crop a UIImage object which I found in the web :
{
        UIGraphicsBeginImageContext(rect.size);
        [image drawAtPoint:rect.origin];
        UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
}
But the result is something wrong. The cropping position is NOT where I expect. How come I have to multiple -1 to both rect.origin’s x and y.
I looked at previous code I wrote before, the code exactly fixed with the multiplication. (I had completely forgot it)

I tried to see any other way in the web, and found this :
{
    CGImageRef srcImageRef = image.CGImage;
    CGImageRef croppedImageRef = CGImageCreateWithImageInRect(srcImageRef, rect);
    UIImage * croppedImage = [UIImage imageWithCGImage: croppedImageRef];
}
cropping a UIImage

↑That’s good. This CGImageCreateWithImageInRect is a new function?, I thought and saw the reference. It said :
Available in iOS 2.0 and later.
Oh, really…
Develop | Comments(0) | Trackback(0)
Comment

管理者のみに表示