如何修复CGContextRestoreGState:无效的上下文0x0 [英] How can I fix CGContextRestoreGState: invalid context 0x0

查看:251
本文介绍了如何修复CGContextRestoreGState:无效的上下文0x0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

This is the code that I am working with:

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

我继续在控制台中收到错误,我不确定该尝试还是不尝试

I continue to get errors in the console, I'm not sure what to try or what is not being done correctly.

推荐答案

上述错误的确切原因:-由于当前上下文大小为零,因此您要添加剪切到当前的上下文,而这并不是真正意义上的。因此上述错误经常发生。

The exact cause of above error :- Since the current context size is zero so you are adding clip to current Context which do not exist in real sense . So above error occurs frequently .

因此检查oldImage在上述函数中是否存在。

因此更新后的代码如下:

so Updated code looks like :

    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
}

这篇关于如何修复CGContextRestoreGState:无效的上下文0x0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆