如何以编程方式绘制到iOS中的显示?

时间:2013-05-14 17:01:38

标签: ios cocoa-touch uiimageview uikit core-graphics

我有一种绘制到屏幕的方法,它对我的​​应用程序有许多好处,除了它根本不起作用的小问题......

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

@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是视图控制器的委托,imageViewUIImageView小部件的出口。我尝试将400 x 400红色框绘制到图像中,并将该图像分配给窗口小部件。我甚至打电话给setNeedsDisplay做好准备。

我做错了什么? 谢谢!

1 个答案:

答案 0 :(得分:3)

这些问题是:

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

删除它们。而是以这种方式设置填充颜色:

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

您遇到问题的原因是您未能创建色彩空间。您需要调用CGContextSetFillColorSpace,但未能这样做。但只有在使用CGContextSetFillColor时才需要这样做。但它已被弃用,所以不要使用它。正如文档所推荐的那样使用CGContextSetFillColorWithColor。它会为您解决色彩空间问题。