【问题标题】:How can I fix CGContextRestoreGState: invalid context 0x0如何修复 CGContextRestoreGState:无效上下文 0x0
【发布时间】:2013-09-19 17:41:09
【问题描述】:

这是我正在使用的代码:

    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();

我继续在控制台中收到错误,我不确定要尝试什么或未正确完成什么。

【问题讨论】:

  • 当您的图像宽度和高度为零时会出现此错误。

标签: ios core-graphics


【解决方案1】:

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

所以检查 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2013-10-30
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多