0

私はスタンフォード大学の 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);
}
4

1 に答える 1

2

代わりにCGContextSaveGStateandが必要です。CGContextRestoreGState次のコードが機能します。

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor greenColor] setFill];
    [[UIColor blackColor] setStroke];
    [self drawBlueCircle:context];
    CGContextMoveToPoint(context, 55, 5);
    CGContextAddLineToPoint(context, 105, 100);
    CGContextAddLineToPoint(context, 5, 100);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
}

- (void)drawBlueCircle:(CGContextRef)context {
    CGContextSaveGState(context);
    [[UIColor blueColor] setFill];
    CGContextAddEllipseInRect(context, CGRectMake(0, 0, 100, 100));
    CGContextDrawPath(context, kCGPathFillStroke);
    CGContextRestoreGState(context);
}

ソース

于 2012-09-05T13:28:44.693 に答える