2011-02-15 77 views
8

我有一個視圖,它有內容是圖像的子圖層。從視圖的圖層獲取UIImage?

我希望通過myView.image獲得視圖的圖像,但顯然該視圖沒有圖像只是圖層。

如何從視圖的圖層創建UIImage?

回答

19
UIGraphicsBeginImageContext(yourView.bounds.size); 
[yourView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

注意:您需要爲此包含QuartzCore。

1
CGRect myRect =CGRectMake(0, 0, 300, 300);// [self.view bounds]; 
UIGraphicsBeginImageContext(myRect.size); 

CGContextRef ctx = UIGraphicsGetCurrentContext(); 
[[UIColor blackColor] set]; 
CGContextFillRect(ctx, myRect); 

[self.view.layer renderInContext:ctx]; 
UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();