注意:控件不要使用SafeArea约束,不然获取的快照内容不准确
Swift
private func launchScreenSnapshort() -> UIImage? {
guard let info_dict = Bundle.main.infoDictionary,
let storyboard_name = info_dict["UILaunchStoryboardName"] as? String,
let storyboard_vc = UIStoryboard.init(name: storyboard_name, bundle: nil).instantiateInitialViewController(),
let storyboard_view = storyboard_vc.view else {
return nil
}
let size = storyboard_view.bounds.size
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let ctx = UIGraphicsGetCurrentContext()
storyboard_view.layer.render(in: ctx!)
let lauch_image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return lauch_image
}
Objective-C
- (UIImage *)imageFromLaunchScreen {
NSString *UILaunchStoryboardName = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchStoryboardName"];
if (UILaunchStoryboardName == nil) {
NSLog(@"从 LaunchScreen 中获取启动图失败!");
return nil;
}
UIViewController *LaunchScreenSb = [[UIStoryboard storyboardWithName:UILaunchStoryboardName bundle:nil] instantiateInitialViewController];
if (LaunchScreenSb) {
UIView * view = LaunchScreenSb.view;
// 加入到UIWindow后,LaunchScreenSb.view的safeAreaInsets在刘海屏机型才正常。
UIWindow *containerWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
view.frame = containerWindow.bounds;
[containerWindow addSubview:view];
[containerWindow layoutIfNeeded];
UIImage *image = [self imageFromView:view];
containerWindow = nil;
return image;
}
NSLog(@"从 LaunchScreen 中获取启动图失败!");
return nil;
}
-(UIImage *)imageFromView:(UIView*)view {
//fix bug:https://github.com/CoderZhuXH/XHLaunchAd/issues/203
if (CGRectIsEmpty(view.frame)) {
return nil;
}
CGSize size = view.bounds.size;
//参数1:表示区域大小 参数2:如果需要显示半透明效果,需要传NO,否则传YES 参数3:屏幕密度
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
}else{
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
}
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
网友评论