1
votes

Usually when you draw in a invalid context, you see something like invalid context 0x00, but this is not the case, as I see an address. And all my Core Graphics code is inside drawRect of a view. Sometimes, not always, I see: ": CGContextFillRects: invalid context 0xa88a500" Sometimes it seems my code works but others fail. What I want to draw is something like a mask.

Can you tell me if you see anything wrong here?:

UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]); CGContextFillRect(context, rect);

switch (shape) {
    case SHAPE_ELIPSE:
        //
        CGContextAddEllipseInRect(context, maskBox);
        CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
        CGContextFillEllipseInRect(context, maskBox);
        break;
    case SHAPE_SQUARE:
        //
        CGContextAddRect(context, maskBox);
        CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
        CGContextFillRect(context, maskBox);
        break;
    default:
        break;
}
CGContextStrokePath(context);
UIImage *backGroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef maskRef = backGroundImage.CGImage;

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), NULL, false);

UIGraphicsBeginImageContext(rect.size);
CGContextRef contextBlack = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(contextBlack, [[UIColor blackColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *blackImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef masked = CGImageCreateWithMask([blackImage CGImage], mask);
CGImageRelease(mask);
[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithCGImage:masked]]];
CGImageRelease(masked);

Thanks a lot.

2

2 Answers

1
votes

Calling UIGraphicsEndImageContext() would invalidate the context context. However, your program continues to use that variable. IOW, you should reassign context after calling UIGraphicsBeginImageContext() the second time:

context = UIGraphicsGetCurrentContext();
1
votes

In addition to Justin answer: no need to place your code inside drawRect. It will be called more than once and you only need to redraw you pattern background when "shape" changes.

Call the code in setShape.