在 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
.
感谢您的帮助,但我无法让我的程序运行并且很困惑。我不再收到以前遇到的错误,但我现在只看到一个空白屏幕。我试过了setNeedsDisplay
,setNeedsDisplayInRect
但它们似乎都不起作用。
这是我的一个功能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);
}
}
}
}