2017-02-07 58 views
0

我錯過了什麼?被卡住了幾個小時,drawRect按預期繪製,getViewImage()從viewcontoller中調用UIGraphicsGetImageFromCurrentImageContext()返回nil;嘗試了很多變化。 任何幫助表示讚賞。IOS Quartz2D無法從當前上下文中獲取圖像

- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    UIGraphicsBeginImageContext(self.bounds.size); 
    CGContextSetLineWidth(context, 5.0); 
    CGContextSetStrokeColorWithColor(context, [[UIColor blackColor]CGColor]); 
    CGContextMoveToPoint(context,100.0,100.0); 
    CGContextAddLineToPoint(context,200.0,200.0); 
    CGContextMoveToPoint(context,200.0,200.0); 
    CGContextAddLineToPoint(context,200.0,400.0); 
    CGContextStrokePath(context); 
} 


-(UIImage *)getTheImage 
{ 
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext(); 
    NSLog(@"drawImage %@",drawImage); 
    return drawImage; 
} 

回答

0

只有當基於位圖的圖形上下文是當前圖形上下文,您應該調用這個函數。如果當前上下文爲零,或者不是通過調用UIGraphicsBeginImageContext創建的,則此函數返回nil。

顯然你的電話不在上下文中。

0

你可以試試嗎?

-(UIImage *)getTheImage 
{ 
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale); 
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; 
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    NSLog(@"drawImage %@",drawImage); 
    return drawImage; 
} 
+0

感謝您的迴應,仍然無法正常工作UIGraphicsBeginImageContext僅需要1個參數。 –

+0

已將UIGraphicsBeginImageContext更改爲UIGraphicsBeginImageContextWithOptions,仍然不行 –

+0

對UIGraphicsBeginImageContextWithOptions抱歉。你能告訴我你從哪裏調用這個getTheImage方法嗎?我從視圖控制器的viewWillAppear和viewDidAppear方法中調用了這個方法,並且從這兩個地方的圖像都不是零。 但是,當我從viewDidLoad調用此方法時,圖像即將變爲零。 只有完全加載視圖後,才應調用getTheImage方法。 –