iOS:是否可以捕获启动画面的图像?

时间:2017-01-09 09:13:44

标签: ios calayer splash-screen

我尝试使用以下代码捕获并在application:didFinishLaunchingWithOptions:内保存启动画面的图像:

UIWindow *w = [[[UIApplication sharedApplication] windows] firstObject];

UIGraphicsBeginImageContext(w.bounds.size);
[w.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
NSString *storePath = [NSString stringWithFormat:@"%@/%ld.png", applicationDocumentsDir, unixTime];
[UIImagePNGRepresentation(img) writeToFile:storePath atomically:YES];

但遗憾的是,图片会另存为透明图片。这可能是因为我的 UIWindow 对象不正确。有人可以指导我继续吗?

2 个答案:

答案 0 :(得分:0)

LaucnhScreen.storyboard 文件视图控制器设置故事板ID后,为什么不尝试以下代码。

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"LaunchScreen"
                                                             bundle: nil];

    UIViewController *controller = (UIViewController*)[mainStoryboard
                                                       instantiateViewControllerWithIdentifier: @"Launch"];
    UIGraphicsBeginImageContext(w.bounds.size);
    [controller.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
    NSString *storePath = [NSString stringWithFormat:@"%@/%ld.png", applicationDocumentsDir, unixTime];
    [UIImagePNGRepresentation(img) writeToFile:storePath atomically:YES];

答案 1 :(得分:0)

关于answer UIApplicationDelegate通常引用“主窗口”:

[[[UIApplication sharedApplication] delegate] window];