当 View 加载到我的 iOS 应用程序中时,我动态创建一个 UIImageView 并将我的图像放置在其中。我想在 UIImageView 顶部画一个简单的圆圈,但到目前为止还无法这样做。
我编写了这段代码,并尝试在从另一个对象接收到事件时画一个圆圈...
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 0, 0, 255, 0.5);
CGContextFillRect(context, CGRectMake(10, 10, 10, 10));
...但是什么也没发生 我收到错误。
<Error>: CGContextSetRGBStrokeColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0
我试图在一切之上绘制,但无济于事。我做错了什么?
最佳答案
attempted to draw a circle upon recieving an event from another object. [emphasis mine]
您的CGContextRef
为NULL
,因为您调用UIGraphicsGetCurrentContext
的地方没有图形上下文。
当您位于 View 的 drawRect:
中时,已经为您设置了上下文,因此您可以进行绘制,并且可以在需要时获取当前上下文。然而,在任意方法(例如 IBAction)中,可能没有可供您绘制的图形上下文。您需要创建一个,也许使用 UIGraphicsBeginImageContextWithOptions
,或者(最好)只是在事件处理程序方法中设置一个标志,以指示下次应该通过 drawRect:
绘制一些额外的内容,然后调用 setNeedsDisplay
。
关于ios - 在 UIImageView 上绘制一个简单的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5683492/