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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With