Set graphics context to display UIImage (Obj-C)
Asked Answered
V

2

1

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!

Varela answered 28/1, 2010 at 23:1 Comment(1)
create your object by using the constructor that takes a "rect" as parameter or create your object frame rect before you draw anything.Crookes
J
3

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.

Jeweljeweler answered 29/1, 2010 at 19:22 Comment(0)
D
2

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

Digitize answered 28/1, 2010 at 23:27 Comment(3)
and use UIGraphicsGetCurrentContext() for the contextWellfixed
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.Varela
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 :-)Varela

© 2022 - 2024 — McMap. All rights reserved.