なぜ Quartz 2D グラフィックス コンテキスト関数は drawRect メソッド内から呼び出さなければならないのですか?
drawRect 以外の場所から CGGraphics コンテキスト関数を呼び出すと、次のようなメッセージが表示されるためです。
<Error>: CGContextFillRects: invalid context
<Error>: CGContextSetFillColorWithColor: invalid context
実際、UIView のサブクラスでは、Render というメソッドで Graphics Context をセットアップします。Render が呼び出されると、上記のエラーが発生します。
- (void)Render {
CGContextRef g = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(g, [UIColor blueColor].CGColor);
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
[@"It works!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
NSLog(@"gsTest Render");
}