在iOS中通过代码获得启动图片

2019-05-27  本文已影响0人  MichealXXX
一般我们很少会通过代码去获取启动图片,很多时候是在自定义广告页的时候会用到,比如在网络加载的过程中我们要先显示本地的默认启动图,这时候就要通过代码去获得启动图,手动控制启动图消失的时机,当然也不排除有些思路惊奇的产品经理会弄出这种需求。
我们都知道,设置启动图有两种方式,一种是在LaunchScreen.storyboard中直接设置,另外一种是在Assets中设置LaunchImage,话不多说,直接贴代码。
通过代码获得LaunchScreen.storyboard中的启动图
/** 获取启动图片 */
- (UIImage *)getLaunchImage
{
    NSString *UILaunchStoryboardName = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchStoryboardName"];
    if(UILaunchStoryboardName == nil){
        
        return nil;
    }
    UIViewController *LaunchScreenSb = [[UIStoryboard storyboardWithName:UILaunchStoryboardName bundle:nil] instantiateInitialViewController];
    if(LaunchScreenSb){
        UIView * view = LaunchScreenSb.view;
        view.frame = [UIScreen mainScreen].bounds;
        UIImage *image = [self imageFromView:view];
        return image;
    }

    return nil;
}

-(UIImage*)imageFromView:(UIView*)view{
    CGSize size = view.bounds.size;
    //参数1:表示区域大小 参数2:如果需要显示半透明效果,需要传NO,否则传YES 参数3:屏幕密度
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
通过代码获得LaunchImage中的启动图
/** 获取启动图片 */
- (UIImage *)getLaunchImage
{
    CGSize viewSize = [UIScreen mainScreen].bounds.size;
    NSString *viewOrientation = @"Portrait";                // 横屏请设置为 @"Landscape"
    UIImage *lauchImage = nil;
    NSArray *imagesDictionary = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary *dict in imagesDictionary)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            lauchImage = [UIImage imageNamed:dict[@"UILaunchImageName"]];
        }
    }
    return lauchImage;
}
以上就是通过代码获取两种启动图的方式,希望可以帮助到大家,以备不时之需。
上一篇下一篇

猜你喜欢

热点阅读