在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);
}
}
}
}
答案 0 :(得分:0)
您的代码非常接近!但是,用于实例化ChessBoard实例的代码是不正确的。 UIView的文档指出你必须使用initWithFrame:initializer方法,而不是使用“new”(在Objective-C中总是应该避免)。
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect boardFrame = CGRectMake(0, 0, 240, 240);
ChessBoard *theBoard = [[ChessBoard alloc] initWithFrame:boardFrame];
[self.view addSubview:theBoard];
}
如果您尝试这样做,您应该看到您的绘图代码正常工作。