使一个UIView添加子视图到一个单一的图像?

我有添加子视图的观点。 我想用许多子视图把这个观点转换成一个图像或视图。

这怎么可能?
谢谢

在iOS7上,您可以使用新的[UIView snapshotViewAfterScreenUpdates:]方法。

要支持较旧的操作系统,您可以将任何视图渲染到具有Core Graphics的UIImage中。 我在UIView上使用这个类别来获取快照:

UView+Snapshot.h

 #import <UIKit/UIKit.h> @interface UIView (Snapshot) - (UIImage *)snapshotImage; @end 

UView+Snapshot.m

 #import "UIView+Snapshot.h" #import <QuartzCore/QuartzCore.h> @implementation UIView (Snapshot) - (UIImage *)snapshotImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0); [self.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultingImage; } @end 

它需要QuartzCore框架,所以一定要把它添加到你的项目中。

要使用它,请导入标题和:

 UIImage *snapshot = [interestingView snapshotImage]; 

确实有可能,使用Core Graphics的渲染函数将视图渲染到上下文中,然后用该上下文的内容初始化图像。 看到这个问题的答案是一个很好的技术。

这里是Vytis例子的一个快速的2.x版本

 extension UIView { func snapshotImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0) self.layer.renderInContext(UIGraphicsGetCurrentContext()!) let resultingImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultingImage } }