gpt4 book ai didi

ios - UIGraphicsGetCurrentContext() : Should we put CGContext as function parameter

转载 作者:行者123 更新时间:2023-11-29 10:39:30 25 4
gpt4 key购买 nike

我正在使用 Core Graphic 库在方法 drawRect 下的 UIView 上绘图。正如我们所知,在这种方法下,我们首先通过以下方式获取上下文:

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

我经常使用辅助方法来绘图。所以,在辅助方法中,我应该把这个上下文作为参数吗?例如:

- drawCircle:(CGContextRef)context center:(int)center radius:(int)radius {
// drawing here
}

或者我们可以稍后在辅助函数中获取上下文变量:

- drawCircle: center:(int)center radius:(int)radius {
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing here
}

我测试过,通常没有发现任何问题。但我担心,当我调用另一个方法时,某些东西会发生变化,UIGraphicsGetCurrentContext() 将返回不同的上下文变量。那么以第二种方式安全吗?因为它会让我的代码更清晰。如果错了,请告诉我在什么情况下会错?

谢谢:)

最佳答案

好问题。我在 UIGraphicsGetCurrentContext 的文档中注意到它说:

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current. If you are not using a UIView object to do your drawing, however, you must push a valid context onto the stack manually using the UIGraphicsPushContext function.

In iOS 4 and later, you may call this function from any thread of your app.

这听起来像是在暗示这个函数是线程安全的,一般来说,对于线程来说,你会担心如果你在不同的地方访问相同的函数或属性,你可能会访问不同的东西,或者他们可能不会正确同步,因此您可能会从两个不同的地方获取不同的信息。

我会假设,如果它暗示这个函数是线程安全的,那么如果你从不同的函数访问它应该无关紧要,因为它应该给你相同的结果,特别是如果你甚至没有使用线程,所以也许这更像是一个偏好问题?

就是说,在该引用的第一段中,第二句话提到手动将有效上下文插入堆栈。如果您在传递上下文的地方编写 drawCircle 代码,那么您似乎具有更大的灵 active ,因为您可以传递不同的上下文(如果出于某种原因有用),但是如果您进行硬编码,则只能使用 UIGraphicsGetCurrentContext() 返回的默认上下文.

这是文档的链接:UIGraphicsGetCurrentContext Documentation

关于ios - UIGraphicsGetCurrentContext() : Should we put CGContext as function parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25201886/

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