在视图或委托中插入图像

时间:2013-12-07 05:38:43

标签: drawrect setneedsdisplay

现在我的代码是app委托,视图控制器和主视图 现在我只是想插入一个大图像作为背景,但我无法弄清楚它放在哪里,我在运行模拟时遇到错误

 <Error>: CGContextRestoreGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.


- (void) applicationDidBecomeActive: (UIApplication *) application {
    NSLog(@"AAAAAAAAAA");
    [self startGameLoop];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"AAAAA");
    mainView = [[MainView alloc] initWithFrame: [UIScreen mainScreen].applicationFrame];
    mainView.backgroundColor = [UIColor grayColor];
    [self.window addSubview: mainView];
    [self.window makeKeyAndVisible];
    [self startGameLoop];
    return YES;
}



    - (void) startGameLoop {
    quack = [NSTimer scheduledTimerWithTimeInterval:.0303 target:self selector:@selector(loop)       userInfo:nil repeats:YES];
    NSLog(@"Game Loop timer instance: %@", quack);
    mainView.backgroundColor = [UIColor grayColor];
}

- (void) loop {
    NSLog(@"BBBBBB");
    pic = [UIImage imageNamed:@"f1.png"];
    [pic drawAtPoint:CGPointMake(160, 0)];
    [mainView setNeedsDisplay];

}

- (void) drawRect: (CGRect) rect {
    maps = [UIImage imageNamed:@"map.png"];
    [maps drawAtPoint:CGPointMake(W/2, 0)];

}

1 个答案:

答案 0 :(得分:0)

您正在调用一种方法([pic drawAtPoint:]),该方法需要在图形上下文之外使用“当前”图形上下文。在调用drawRect之前,UIKit会自动在幕后创建一个:。

此外,您的drawRect必须位于MainView类中,而不是UIApplicationDelegate中。

尝试从循环中删除[pic drawAtPoint:CGPointMake(160,0)]。 如果要在每个循环中绘制它,则必须在MainView类中的drawRect方法中完成。

另外,您提到您正在使用视图控制器,但我在您的代码中看不到任何引用。

但是如果您只想移动图像,可能需要考虑不调用setNeedsDisplay。而是创建一个UIImageView,将其添加到您的视图,并在循环方法中设置其中心属性。