问题
I'm trying to render a UIImage in Objective-C (working on a simple iPhone app (breakout-type thing) to get used to the environment). However, I'm getting an "Error: CGContextDrawImage: invalid context" error when I try and draw it.
My question is: how do I set the context that the DrawAtPoint method of UIImage uses?
Here the relevant code for how I'm initializing / calling everything:
@interface GameItem : NSObject
{
IBOutlet UIImage * sprite;
CGPoint pos;
}
- (id) initWithPositionAndSprite: (CGPoint)placementPosition :(UIImage*) blockImage;
- (void) update;
@property CGPoint pos;
@end
in update:
[sprite drawAtPoint:pos];
And initializing it like:
newBall = [[Ball alloc] initWithPositionAndSprite:CGPointMake(3.0, 4.0) :[UIImage imageNamed:@"ball.png"]];
(Ball inherits from GameItem, doesn't do anything different just yet)
I'm getting the invalid context from the drawAtPoint call afaik. Any help/pointers to somewhere that will explain how to set the context would be greatly appreciated.
Thanks!
回答1:
If this is to be drawn to the screen, you'll need to locate your drawing code within the -drawRect:
method of a UIView
(or –drawInContext:
of a CALayer
). To update its contents, you'd need to call -setNeedsDisplay
on the UIView
or CALayer
. Attempting drawing at any other time will cause the "invalid context" error you're seeing.
回答2:
Try wrapping the call in UIGraphicsBeginImageContext()
and UIGraphicsEndImageContext()
.
来源:https://stackoverflow.com/questions/2158677/set-graphics-context-to-display-uiimage-obj-c