Set graphics context to display UIImage (Obj-C)

人走茶凉 提交于 2019-12-11 05:48:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!