2010-02-19 53 views
1

這是我的主要看法,我只是希望它吸取一些東西來測試,但我發現我的UI沒有任何東西,這裏是代碼:爲什麼我不能在我的UIView上繪製一些東西?

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextMoveToPoint(context, 100.0f, 100.0f); 
    CGContextAddLineToPoint(context, 200.0f, 200.0f); 
    CGContextStrokePath(context); 


} 

這是我複製的代碼示例線上。我假設代碼是正確的,它沒有任何錯誤,但沒有出現。或者......這段代碼不應該粘貼在viewDidLoad上?

回答

4

viewDidLoad沒有上下文。您將需要創建一個圖像內容,做你的圖紙,產生的圖像,然後將其添加到視圖,像這樣:

UIGraphicsBeginImageContext(); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSetLineWidth(context, 2.0); 
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
CGContextMoveToPoint(context, 100.0f, 100.0f); 
CGContextAddLineToPoint(context, 200.0f, 200.0f); 
CGContextStrokePath(context); 
UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

UIImageView *imgView = [[UIImageView alloc] initWithImage:img]; 
[self.view addSubview:imgView]; 
[imgView release]; 

編輯: viewDidLoad中是一個UIViewController的方法,而不是一個UIView方法。我假設這個代碼在你的控制器中,我是否正確?此外,viewDidLoad僅在從nib加載視圖後調用。你是否使用了一個nib(使用Interface Builder構建的xib)或者是否以編程方式創建了你的視圖?

1

要使用您的代碼繪製視圖,您需要覆蓋-drawRect:而不是-viewDidLoad

- (void)drawRect:(CGRect)rect { 
    [super drawRect:rect]; // not necessary 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextMoveToPoint(context, 100.0f, 100.0f); 
    CGContextAddLineToPoint(context, 200.0f, 200.0f); 
    CGContextStrokePath(context); 


} 
相關問題