2013-05-14 59 views
2

我有一個繪製到屏幕的方法,對於我的應用程序有很多好處,除了它不起作用的小問題...。如何以編程方式繪製到iOS中的顯示?

我有一個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是視圖控制器和imageView的委託爲UIImageView插件的出口。我嘗試在圖像中繪製一個400 x 400的紅色框並將該圖像分配給小部件。我甚至稱setNeedsDisplay爲好措施。

我在做什麼錯? 謝謝!

回答

3

這些線的問題:

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

刪除它們。取而代之的是,設置填充顏色是這樣的:

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

原因您的問題是,你不能創造一個色彩空間。您需要撥打CGContextSetFillColorSpace,但您未能如願。但只有在您使用CGContextSetFillColor時才需要。但它已被棄用,所以不要使用它。按照文檔推薦使用CGContextSetFillColorWithColor。它爲您處理色彩空間問題。

相關問題