图像裁剪在iOS 6.0中无法正常工作.在模拟器中工作正常.

Man*_*ani 5 iphone

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

我正在使用此代码.请给出一些解决方案.谢谢

Mik*_*ler 4

CGImageCreateWithImageInRect无法正确处理图像方向。网上有许多奇怪而美妙的裁剪技术,涉及巨大的 switch/case 语句(请参阅 Ayaz 答案中的链接),但如果您停留在 UIKit 级别并仅使用本身的方法来进行绘图UIImage,那么所有我们会为您照顾到具体细节。

以下方法非常简单,并且适用于我遇到的所有情况:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

opaque如果不需要透明度,您可能需要更改参数的值。