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

问题描述:

我有添加子视图的视图。我想用许多子视图将这个视图转换成单个图像或视图。使添加子视图到一个图像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]; 
+0

Vytis,一切才有意义在这里除了'的UIImage *快照= [ interestingView snapshotImage];'Xcode抱怨:'使用未声明的标识interestingView''。你究竟是如何申明的? – Greg

+1

'interestingView'是你想拍摄快照图像的视图。因此,例如,如果你想拍一个视图控制器视图的快照,你将在你的UIViewController代码中有'UIImage * snapshot = [self.view snapshotImage];' 。 – Vytis

确实有可能,使用Core Graphics的渲染函数将视图渲染到上下文中,然后使用该上下文的内容初始化图像。请参阅this question的答案,以获得一个好的技巧。

这里是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 
    } 
}