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

时间:2012-09-05 12:12:43

标签: iphone

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

我正在使用此代码。请提供一些解决方案。谢谢提前

1 个答案:

答案 0 :(得分:4)

CGImageCreateWithImageInRect无法正确处理图像方向。 网上有许多奇怪而精彩的裁剪技术,包括巨型开关/案例陈述(参见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;
}

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

相关问题