核心图形错误

时间:2013-07-10 15:55:46

标签: iphone ios objective-c core-graphics

当我在自定义UIView子类中调用DrawRect时,我收到以下错误:

CGContextFillRects: invalid context 0x0

我的UIView子类'EVGameView'中的DrawRect方法实现如下:

- (void)drawRect:(CGRect)rect
{
    CGRect rectangle = CGRectMake(0, 100, 320, 100);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(context, rectangle);
}

我在viewController的“viewDidLoadMethod”中实例化我的EVGameView类:

- (void)viewDidLoad
{
    srand(time(0));

    [super viewDidLoad];

    gameBoard = [[EVBoard alloc] init];
    [gameBoard initBoard:10 : 10 : mainBoard];

    gameView = [[EVGameView alloc] init];          // EVGameView instance

            .
            .
            .

}

我用以下方法调用drawRect方法:

- (void)drawStartPosition
{
    CGRect rect;
    rect.origin = startPos;
    rect.size.width = 10;
    rect.size.height = 10;
    [gameView drawRect: rect];
}

似乎没有设置上下文,因为UIGraphicsGetCurrentContext()返回'nil'。我在youTube上看过一些例子,人们有一个相同的drawRect方法,它工作正常。我在.xib文件中设置了一个单独的视图,并将其链接到我的gameView实例,但仍然没有运气。 对此有任何帮助非常感谢!

谢谢 -

1 个答案:

答案 0 :(得分:0)

你没有说你在哪里打电话drawStartPosition,但这就是问题所在。基本上,您不应该自己调用drawRect:,而是应该调用setNeedsDisplay并允许系统在实际请求您的视图将自己绘制到提供的上下文之前完成所有适当的设置。