2013-09-19 3 views
4

Это код, который я работаю с:Как я могу исправить CGContextRestoreGState: недопустимый контекст 0x0

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

Эта ошибка возникает, когда ваша ширина и высота изображения будет равна нулю. – Rajesh

ответ

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 
} 
Смежные вопросы