私はスタンフォード大学の IOS レッスンを受講してきましたが、UIGraphicsPushContext と UIGraphicsPopContext が何をするのか (レッスン 4) を理解することに行き詰まっています。メモから、これらのメソッドを使用して、他のユーティリティ メソッドから現在のグラフィックス状態に影響を与えることを回避できることが説明されています。以下は、メモに記載されている例です。
- (void)drawGreenCircle:(CGContextRef)ctxt {
UIGraphicsPushContext(ctxt);
[[UIColor greenColor] setFill];
// draw my circle
UIGraphicsPopContext();
}
- (void)drawRect:(CGRect)aRect {
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor redColor] setFill];
// do some stuff
[self drawGreenCircle:context];
// do more stuff and expect fill color to be red
}
ただし、これをテストしようとすると、この結果が得られないようです。以下は、drawRect で現在のコンテキストを取得し、色を設定し、色を緑に設定するユーティリティ メソッドを呼び出し、drawRect に戻って線を描画する、簡単なテスト ケースです。スタンドフォード サイトのメモに基づいて、drawGreenCircle でコンテキストをプッシュ/ポップしたため、線が赤くなることが予想されます。(drawGreenCircle で実際に円を描いているわけではないことに気付きました) しかし、drawRect で緑色の線が表示されます。私の drawGreenCircle メソッドは色を変更し、赤に戻さなかったようです。この概念について何が欠けているのか知りたいです。
- (void)drawGreenCircle:(CGContextRef)ctxt {
//Doesn't actually draw circle --Just testing if the color reverts
//to red in drawRect after this returns
UIGraphicsPushContext(ctxt);
[[UIColor greenColor] setStroke];
UIGraphicsPopContext();
}
- (void)drawRect:(CGRect)aRect {
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor redColor] setStroke];
// do some stuff
[self drawGreenCircle:context];
CGContextBeginPath(context);
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 500, 100);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
}