Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have a CALayer with many sublayers. When setNeedsDisplay is called on a sublayer, I get an invalid context error

I just rewrote my game to use core animation in an effort to make it faster. I have a UIView with a layer that contains many sublayers (the game "tiles"). The tile sublayers are actually CALayer subclasses that draw their own content using drawInContext:. When a tile is selected, for example, it needs to be redrawn, so I call [tileLayer setNeedsDisplay] and I get a bunch of invalid context errors. If I call [mainView setNeedsDisplay] or [mainView.layer setNeedsDisplay], none of the tiles redraw. How can I get an individual tile (CALayer subclass) to redraw?

EDIT: From the very helpful comments, I was able to figure out the this only happens when the CALayer subclass is drawing an image. Here are the errors:

<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetBlendMode: invalid context 0x0
<Error>: CGContextSetAlpha: invalid context 0x0
<Error>: CGContextTranslateCTM: invalid context 0x0
<Error>: CGContextScaleCTM: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0

Here is the line of code that causes the errors:

[[UIImage imageNamed:@"flag.png"] drawInRect:self.bounds];

Is there another way I should be drawing an image in a CALayer subclass?

like image 365
danjonweb Avatar asked Dec 06 '25 18:12

danjonweb


1 Answers

Core Animation doesn't know about UIKit, i.e. drawInContext: doesn't set the CALayer context as UIKit's current context. The drawInRect: method in UIImage draws the image on this current context. To manually push a context to UIKit, use UIGraphicsPushContext() and pop it using UIGraphicsPopContext() when done.

For example:

UIGraphicsPushContext(context);
[[UIImage imageNamed:@"flag.png"] drawInRect:self.bounds];
UIGraphicsPopContext();
like image 62
Jerson Perpetua Avatar answered Dec 08 '25 07:12

Jerson Perpetua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!