Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image crop not properly working in iOS 6.0. Working fine in simulator.

Tags:

iphone

- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return cropped;
}

I am Using this code. Please give some solutions.Thanks in advance

like image 561
Mani Avatar asked Oct 06 '22 17:10

Mani


1 Answers

CGImageCreateWithImageInRect does not handle image orientation correctly. There are many strange and wonderful cropping techniques out there on the net involving giant switch/case statements (see the links in Ayaz's answer), but if you stay at the UIKit-level and use only methods on UIImage itself to do the drawing, all the nitty gritty details are taken care for you.

The following method is as simple as you can get and works in all cases that I have encountered:

- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect
{
    if (UIGraphicsBeginImageContextWithOptions) {
        UIGraphicsBeginImageContextWithOptions(rect.size,
                                               /* opaque */ NO,
                                               /* scaling factor */ 0.0);
    } else {
        UIGraphicsBeginImageContext(rect.size);
    }

    // stick to methods on UIImage so that orientation etc. are automatically
    // dealt with for us
    [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}

You may want to change the value of the opaque argument if you don't need transparency.

like image 91
Mike Weller Avatar answered Oct 10 '22 02:10

Mike Weller