【问题标题】:How do i set a CGContextRef property rather than using UIGraphicsGetCurrentContext()如何设置 CGContextRef 属性而不是使用 UIGraphicsGetCurrentContext()
【发布时间】:2012-03-04 04:28:42
【问题描述】:

我一直在尝试使用 UIGraphicsGetCurrentContext 和 CGContextRef。有人告诉我,多次使用 UIGraphicsGetCurrentContext() 是不好的,而是使用 CGContextRef 并引用它。

我一直在尝试处理第二部分,但在设置 @property 和引用它时遇到问题。有人可以给我一个声明和使用示例吗?尝试谷歌搜索,找不到任何参考。

【问题讨论】:

    标签: objective-c xcode core-graphics


    【解决方案1】:

    您可能不应该将来自UIGraphicsGetCurrentContext 的返回值存储在属性中。您通常要么不知道上下文的有效期有多长,要么上下文的生命周期很短。例如,如果您从drawRect: 方法调用UIGraphicsGetCurrentContext,您不知道从drawRect: 返回后该上下文将存在多长时间。如果您在调用UIGraphicsBeginImageContextWithOptions 之后再调用UIGraphicsGetCurrentContext,那么您可能很快就会调用UIGraphicsEndImageContext。保留对这些上下文的引用是不合适的。

    如果您在同一个上下文中调用多个 Core Graphics 函数,那么您希望将上下文存储在一个局部变量中。例如,这是我的一个测试项目中的drawRect: 方法:

    - (void)drawRect:(CGRect)dirtyRect {
        NSLog(@"drawRect:%@", NSStringFromCGRect(dirtyRect));
        [self layoutColumnsIfNeeded];
        CGContextRef gc = UIGraphicsGetCurrentContext();
        CGContextSaveGState(gc); {
            // Flip the Y-axis of the context because that's what CoreText assumes.
            CGContextTranslateCTM(gc, 0, self.bounds.size.height);
            CGContextScaleCTM(gc, 1, -1);
            for (NSUInteger i = 0, l = CFArrayGetCount(_columnFrames); i < l; ++i) {
                CTFrameRef frame = CFArrayGetValueAtIndex(_columnFrames, i);
                CGPathRef path = CTFrameGetPath(frame);
                CGRect frameRect = CGPathGetBoundingBox(path);
                if (!CGRectIntersectsRect(frameRect, dirtyRect))
                    continue;
    
                CTFrameDraw(frame, gc);
            }
        } CGContextRestoreGState(gc);
    }
    

    您可以看到我在上下文中做了很多事情:我正在保存和恢复图形状态,我正在更改 CTM,我正在向其中绘制一些 Core Text 框架。我没有多次调用UIGraphicsGetCurrentContext,而是只调用一次并将结果保存在名为gc 的局部变量中。

    【讨论】:

    • 谢谢,这基本上是推荐的方式。特别是始终以这种方式动态获取上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 2018-07-20
    相关资源
    最近更新 更多