从视图的图层获取UIImage?

问题描述:

我有一个视图,它有内容是图像的子图层。从视图的图层获取UIImage?

我希望通过myView.image获得视图的图像,但显然该视图没有图像只是图层。

如何从视图的图层创建UIImage?

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

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

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();