如何修复CGContextRestoreGState:无效的上下文0x0

时间:2013-09-19 17:41:09

标签: ios core-graphics

这是我正在使用的代码:

    CGRect imageRect = CGRectMake(0, 0, oldImage.size.width, oldImage.size.height);

    CGRect newRect = imageRect;

    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, oldImage.scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -(newRect.size.height));
    CGContextSaveGState(ctx);
    CGContextClipToMask(ctx, newRect, oldImage.CGImage);
    CGContextSetFillColorWithColor(ctx, [UIColor colorWithWhite:0 alpha:0].CGColor);
    CGContextFillRect(ctx, newRect);
    CGContextRestoreGState(ctx);
    CGContextClipToMask(ctx, imageRect, oldImage.CGImage);

    CGContextSetFillColorWithColor(ctx, tintColor.CGColor);

    CGContextFillRect(ctx, imageRect);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

我继续在控制台中出错,我不确定要尝试什么或者没有正确完成。

1 个答案:

答案 0 :(得分:0)

上述错误的确切原因: - 由于当前上下文大小为零,因此您要将剪辑添加到当前上下文中,而实际上并不存在。所以上面的错误经常发生。

因此请检查上面的函数中是否存在oldImage。

所以更新后的代码如下:

    if ( oldImage = [UIImage imageNamed:@"oldImage.png"]) {

        CGRect imageRect = CGRectMake(0, 0, oldImage.size.width, oldImage.size.height);
        CGRect newRect = imageRect;
        UIGraphicsBeginImageContextWithOptions(newRect.size, NO, oldImage.scale);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(ctx, 1, -1);
        CGContextTranslateCTM(ctx, 0, -(newRect.size.height));
        CGContextSaveGState(ctx);
        CGContextClipToMask(ctx, newRect, oldImage.CGImage);
        CGContextSetFillColorWithColor(ctx, [UIColor colorWithWhite:0 alpha:0].CGColor);
        CGContextFillRect(ctx, newRect);
        CGContextRestoreGState(ctx);
        CGContextClipToMask(ctx, imageRect, oldImage.CGImage);
        CGContextSetFillColorWithColor(ctx, tintColor.CGColor);
        CGContextFillRect(ctx, imageRect);
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext(); 
     }
     else {
     //image do not exist
     // Unable to change into New Image
}