views:

569

answers:

2

Hi,

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  A: 

Try wrapping the call in UIGraphicsBeginImageContext() and UIGraphicsEndImageContext().

Ole Begemann
and use UIGraphicsGetCurrentContext() for the context
nathanjosiah
That resolves the error, but it's still not being displayed on the screen. The draw method now looks like this: UIGraphicsBeginImageContext(sprite.size); [sprite drawAtPoint:pos]; UIGraphicsEndImageContext();Not sure exactly what I need to pass into UIGraphicsBeginImageContext(), though other examples I found simply passed the image size.
DashRantic
Also, @nathanjosiah: I'm not sure what good getting the context like that does me, since it's not an argument to any of the UIImage draw methods that I can find--what exactly should I be doing with it? Thanks :-)
DashRantic
A: 

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.

Brad Larson