gpt4 book ai didi

iphone - 使用 UIGraphicsPushContext(context) 和 UIGraphicsPopContext()

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:13:16 26 4
gpt4 key购买 nike

理解 UIGraphicsPushContext(context) 和 UIGraphicsPopContext() 非常令人沮丧

我的理解是,我可以设置上下文的属性,例如笔触颜色,然后将上下文压入堆栈,这样我就可以为当前上下文设置新的颜色。完成后,我可以通过弹出上下文返回到上下文。

下面是我的代码。当我运行下面的代码时,两条线以蓝色绘制。我期望发生的是:我首先将颜色设置为绿色。转到 blueLine 函数并推送绿色上下文。用蓝色画。然后弹出绿色上下文。允许 drawLine 函数以绿色绘制。

这是绘制内容的屏幕截图(两条蓝线):http://dl.dropbox.com/u/1207310/iOS%20Simulator%20Screen%20shot%20Feb%205%2C%202012%209.00.35%20PM.png

非常感谢任何帮助!谢谢。

- (void)drawBlueLine:(CGContextRef)context
{
UIGraphicsPushContext(context);
[[UIColor blueColor] setStroke];
CGContextBeginPath(context);
CGContextMoveToPoint(context, self.bounds.origin.x, 100);
CGContextAddLineToPoint(context, self.bounds.origin.x+self.bounds.size.width, 200);
CGContextStrokePath(context);
UIGraphicsPopContext();
}

- (void)drawLine:(CGContextRef)context
{
UIGraphicsPushContext(context);
CGContextBeginPath(context);
CGContextMoveToPoint(context, self.bounds.origin.x, 200);
CGContextAddLineToPoint(context, self.bounds.origin.x+self.bounds.size.width, 300);
CGContextStrokePath(context);
UIGraphicsPopContext();
}

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();

[[UIColor redColor] setStroke];
CGContextSetLineWidth(context, 5.0);
[self drawBlueLine:context];
[self drawLine:context];
}

或者这不应该起作用吗?

- (void)drawLine:(CGContextRef)oldContext
{

UIGraphicsPushContext(oldContext); //makes oldContext the current context but there is a copy on the stack
[[UIColor blueColor] setStroke];
CGContextBeginPath(oldContext);
CGContextMoveToPoint(oldContext, self.bounds.origin.x, 200);
CGContextAddLineToPoint(oldContext, self.bounds.origin.x+self.bounds.size.width, 300);
CGContextStrokePath(oldContext);

UIGraphicsPopContext(); //previous oldContext is moved back into place containing red?
}

- (void)drawRect:(CGRect)rect
{

CGContextRef oldContext = UIGraphicsGetCurrentContext();

[[UIColor redColor] setStroke];
[self drawLine:oldContext];
//anything I draw here should be red. Shouldn't it?`

最佳答案

UIGraphicsPushContextUIGraphicsPopContext 的作用是更改用于绘图的上下文,不一定保存和恢复任何给定上下文的状态。你的代码所做的只是简单地用你用 UIGraphicsGetCurrentContext 获取的上下文重复替换调用 drawRect: 之前的上下文(它们可能是相同的反正)。

如果您想保存并恢复给定上下文的状态,请改用 CGContextSaveGStateCGContextRestoreGState

关于iphone - 使用 UIGraphicsPushContext(context) 和 UIGraphicsPopContext(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com