0

在 XCode 4.6.3 中运行 iOS 程序时,我不断收到一长串错误,如下所示:

Jul 20 13:24:40 ps2xipas3qfe Chess[277] <Error>: CGContextSetRGBFillColor: invalid context 0x0
Jul 20 13:24:40 ps2xipas3qfe Chess[277] <Error>: CGContextFillRects: invalid context 0x0

这是生成错误的代码:

- (void)drawRect: (CGRect)rect {
    //[super drawRect:rect];
    for(int i=0; i<8; i++) {
        for(int j=0; j<8; j++) {
            CGRect TheRect = CGRectMake(i*30+30,j*30+30,30,30);
            CGContextRef context = UIGraphicsGetCurrentContext();
            if(i%2 == j%2) {
                CGContextSetRGBFillColor(context,1.0,0.0,0.0,0.0);
            }
            else {
                CGContextSetRGBFillColor(context,0.0,0.0,0.0,0.0);
            }
            CGContextFillRect(context,TheRect);
        }
    }
}

当我在网上搜索“无效上下文”错误时,我得到的答案是只能从“drawRect”成员函数中检索图形上下文,但这是在“drawRect”函数中,我仍然得到错误。这里的类ChessBoard继承自UIView.


感谢您的帮助,但我无法让我的程序运行并且很困惑。我不再收到以前遇到的错误,但我现在只看到一个空白屏幕。我试过了setNeedsDisplaysetNeedsDisplayInRect但它们似乎都不起作用。

这是我的一个功能ChessViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    ChessBoard* TheBoard = [ChessBoard new];
    [self.view addSubview: TheBoard];
    // [TheBoard setNeedsDisplayInRect: CGRectMake(0,0,400,400)];
    [TheBoard setNeedsDisplay];
}

这是我的一个功能ChessBoard.m

- (void)drawRect: (CGRect)rect {
    [super drawRect:rect];
    UILabel* HelloWorld = [UILabel new];
    HelloWorld.text = @"Hello, World!";
    [HelloWorld sizeToFit];
    HelloWorld.frame = CGRectMake(1,1,100,20);
    [self addSubview:HelloWorld];
    for(int i=0; i<8; i++) {
        for(int j=0; j<8; j++) {
            CGRect TheRect = CGRectMake(i*30+30,j*30+30,30,30);
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextFillRect(context,TheRect);
            if(i%2 == j%2) {
                CGContextSetRGBFillColor(context,1.0,0.0,0.0,1.0);
            }
            else {
                CGContextSetRGBFillColor(context,0.0,0.0,0.0,1.0);
            }
        }
    }
}
4

1 回答 1

0

您的代码非常接近!但是,您用于实例化 ChessBoard 实例的代码不正确。UIView 的文档指出您必须使用 initWithFrame: 初始化方法,而不是使用“new”(无论如何,在 Objective-C 中应该始终避免使用)。

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect boardFrame = CGRectMake(0, 0, 240, 240);
    ChessBoard *theBoard = [[ChessBoard alloc] initWithFrame:boardFrame];
    [self.view addSubview:theBoard];
}

如果您尝试这样做,您应该会看到您的绘图代码正常工作。

于 2013-07-21T00:26:48.850 回答