在 UIImageView 上绘制一个简单的圆圈
当视图加载到我的 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
我试图超越一切,但无济于事。我做错了什么?
When the view loads in my iOS application, I dynamically create a UIImageView and place my Image inside of it. I would like to draw a simple circle on top of the UIImageView, but have been unable to do so thus far.
I wrote this code and attempted to draw a circle upon recieving an event from another object...
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 0, 0, 255, 0.5);
CGContextFillRect(context, CGRectMake(10, 10, 10, 10));
...but nothing happens I receive an error.
<Error>: CGContextSetRGBStrokeColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0
I'm attempting to draw above everything, to no avail. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
CGContextRef
是NULL
,因为您调用UIGraphicsGetCurrentContext
的地方没有图形上下文。当您位于视图的
drawRect:
中时,已经为您设置了上下文,因此您可以进行绘制,并且可以在需要时获取当前上下文。然而,在任意方法(例如 IBAction)中,可能没有可供您绘制的图形上下文。您需要创建一个,也许使用UIGraphicsBeginImageContextWithOptions
,或者(最好)在事件处理程序方法中设置一个标志,以指示下次通过drawRect 绘制一些额外的内容:
,然后调用setNeedsDisplay
。Your
CGContextRef
isNULL
because there is no graphics context in the place that you are callingUIGraphicsGetCurrentContext
.When you're in the
drawRect:
of a view, a context has already been set up for you, so you can draw and can get the current context if you need to. In an arbitrary method (such as anIBAction
) however, there may not be a graphics context for you to draw into. You need to either create one, using perhapsUIGraphicsBeginImageContextWithOptions
, or (preferably) just set a flag in your event handler method to indicate that something extra should be drawn the next time throughdrawRect:
, and then callsetNeedsDisplay
.