使添加子视图到一个图像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];
答
这里是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
}
}
Vytis,一切才有意义在这里除了'的UIImage *快照= [ interestingView snapshotImage];'Xcode抱怨:'使用未声明的标识interestingView''。你究竟是如何申明的? – Greg
'interestingView'是你想拍摄快照图像的视图。因此,例如,如果你想拍一个视图控制器视图的快照,你将在你的UIViewController代码中有'UIImage * snapshot = [self.view snapshotImage];' 。 – Vytis