保存和恢复CGContext [英] Saving and restoring CGContext

查看:102
本文介绍了保存和恢复CGContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存和恢复CGContext以避免第二次进行繁重的绘图计算而我收到错误<错误>:CGGStackRestore:gstack underflow

I'm trying to save and restore a CGContext to avoid doing heavy drawing computations for a second time and I'm getting the error <Error>: CGGStackRestore: gstack underflow.

我做错了什么?这样做的正确方法是什么?

What am I doing wrong? What is the correct way to do this?

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

    if (initialized) {
        CGContextRestoreGState(context);
        //scale context
        return;
    }

    initialized = YES;

    //heavy drawing computation and drawing

    CGContextSaveGState(context);
}


推荐答案

我想你可能会误解什么 CGContextSaveGState() CGContextRestoreGState() do。它们将当前图形状态推送到堆栈并将其弹出,让您转换当前绘图空间,更改线条样式等,然后将状态恢复为设置这些值之前的状态。它不存储绘图元素,如路径。

I think you might be misinterpreting what CGContextSaveGState() and CGContextRestoreGState() do. They push the current graphics state onto a stack and pop it off, letting you transform the current drawing space, change line styles, etc., then restore the state to what it was before you set those values. It does not store drawing elements, like paths.

来自关于CGContextSaveGState()的文档


每个图形上下文维护一个
的图形状态堆栈。请注意,
并非当前绘图
环境的所有方面都是
图形状态的元素。例如,
当前路径不被视为
图形状态的一部分,因此当你调用
CGContextSaveGState()时,不会保存
function。

Each graphics context maintains a stack of graphics states. Note that not all aspects of the current drawing environment are elements of the graphics state. For example, the current path is not considered part of the graphics state and is therefore not saved when you call the CGContextSaveGState() function.

应该在 drawRect的开头重置图形状态堆栈: ,这就是为什么当你尝试从堆栈中弹出图形状态时出现错误的原因。既然你没有推过一个,就没有一个可以弹出。所有这一切都意味着你不能将你的绘图作为图形状态存储在堆栈中,然后在以后恢复。

The graphics state stack should be reset at the start of your drawRect:, which is why you're getting errors when you try to pop a graphics state off the stack. Since you hadn't pushed one on, there was none to pop off. All of this means that you can't store your drawing as graphics state on the stack, then restore it later.

如果你担心的只是缓存你的绘图,这是由 CALayer 为您完成的,它支持您的 UIView (在iPhone上)。如果你正在做的只是移动你的视图,它将不会被重绘。只有手动告诉它才能绘制它。如果你必须更新部分图纸,我建议将静态元素拆分为自己的视图或 CALayers ,以便只重绘更改的部分。

If all you are worried about is caching your drawing, that is done for you by the CALayer that backs your UIView (on the iPhone). If all you are doing is moving your view around, it won't be redrawn. It will only be drawn if you manually tell it to do so. If you do have to update part of the drawing, I recommend splitting the static elements off into their own views or CALayers so that only the part that changes is redrawn.

这篇关于保存和恢复CGContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆