OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UIImageView 上画一个简单的圆圈 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:06
标题: ios - 在 UIImageView 上画一个简单的圆圈

当 View 加载到我的 iOS 应用程序中时,我会动态创建一个 UIImageView 并将我的 Image 放入其中。我想在 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

我试图超越一切,但无济于事。我做错了什么?



Best Answer-推荐答案


attempted to draw a circle upon recieving an event from another object. [emphasis mine]

您的 CGContextRefNULL,因为在您调用 UIGraphicsGetCurrentContext 的地方没有图形上下文。

当您在 View 的 drawRect: 中时,已经为您设置了一个上下文,因此您可以绘制并在需要时获取当前上下文。然而,在任意方法(例如 IBAction)中,可能没有可供您绘制的图形上下文。您需要创建一个,也许使用 UIGraphicsBeginImageContextWithOptions ,或者(最好)只是在您的事件处理程序方法中设置一个标志,以指示下次应该通过 drawRect: 绘制额外的内容,然后调用 setNeedsDisplay

关于ios - 在 UIImageView 上画一个简单的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5683492/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4