ios - 如何在 iOS 中以编程方式绘制到显示屏?

标签 ios cocoa-touch uiimageview uikit core-graphics

我有一种在屏幕上绘图的方法,它对我的​​应用程序有很多好处,除了它根本不起作用的小问题。

我有一个带有 UIImageView 小部件的 iOS 程序,我试图以编程方式绘制它,但当我运行该程序时它看起来只是黑色。这是我的头文件中的导出声明:

@interface TestViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

...这是我的实现:

@implementation TestViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(400, 400), YES, 0.0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGFloat colour[] = { 1, 0, 0, 1 };
    CGContextSetFillColor(context, colour);
    CGContextFillRect(context, CGRectMake(0, 0, 400, 400));

    self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    [self.imageView setNeedsDisplay];

    UIGraphicsEndImageContext();
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

TestViewController 是 View Controller 的委托(delegate),imageViewUIImageView 小部件的导出。我尝试将 400 x 400 的红色框绘制到图像中,并将该图像分配给小部件。我什至调用 setNeedsDisplay 以达到良好的效果。

我做错了什么? 谢谢!

最佳答案

这些行是问题所在:

CGFloat colour[] = { 1, 0, 0, 1 };
CGContextSetFillColor(context, colour);

删除它们。相反,可以这样设置填充颜色:

 CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);

您出现问题的原因是您未能创建色彩空间。您需要调用CGContextSetFillColorSpace,但您没有这样做。但仅当您使用 CGContextSetFillColor 时才需要这样做。但它已被弃用,所以不要使用它。按照文档的建议,使用 CGContextSetFillColorWithColor 。它会为您解决色彩空间问题。

关于ios - 如何在 iOS 中以编程方式绘制到显示屏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16548844/

相关文章:

ios - 将curl命令翻译成NSMutableUrlRequest

ios - 核心数据 - 集合 NSCFSet 在枚举时发生了变异

iphone - iPhone 上 NSFetchRequest 上的 setFetchBatchSize

ios - 如何以编程方式创建带有一部分黑色的 UIImage RGB 渐变

uiview - 更新 UIImageView Swift 的位置

ios - UIBezierPath 撤消绘图重绘 UIImageView 的图像

ios - UILabel 背景颜色泄漏到边框

ios - Objective-C:后退按钮在从 AppsDelegate 呈现/推送 ViewController 后消失

ios - 每天在设定的时间用 swift 重复本地通知

ios - 在 UITextView 中捕获滚动 Action