开发者

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开发者_如何学Python 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜