将UIView添加到单个图像中?

时间:2012-06-21 20:50:21

标签: ios uiview

我有一个添加了子视图的视图。我想将具有许多子视图的视图转换为单个图像或视图。

怎么可能?
感谢

4 个答案:

答案 0 :(得分:4)

在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];

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

Swift 5 ,易于调用

extension UIView {
    var asImg: UIImage? {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}