IOS

关注公众号 jb51net

关闭
首页 > 软件编程 > IOS > IOS 图片存放

IOS 图片存放3种方式的实现

作者:lbs0912

这篇文章主要介绍了IOS 图片存放3种方式的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Image.xcassets

图片直接加入工程中作为Resource

读取方式:创建图片 Resource 文件夹,直接将图片加入到工程中,使用如下方式读取图片

NSString *path = [NSBundle.mainBundle pathForResource:@"xxx" type:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

特性:在 Resource 的图片管理方式中, 所有的图片创建都是通过读取文件数据得到的, 读取一次文件数据就会产生一次 NSData 以及产生一个 UIImage。 当图片创建好后销毁对应的 NSData,当 UIImage 的引用计数器变为 0 的时候自动销毁 UIImage,这样的话就可以保证图片不会长期地存在在内存中

使用场景:由于这种方法的特性, 所以 Resource 的方法一般用在图片数据很大, 图片一般不需要多次使用的情况,比如说引导页背景(图片全屏)

优势:图片不会长期保存在内存当中, 所以不会有很多的内存浪费。同时, 大图一般不会长期使用, 而且大图占用内存一般比小图多了好多倍, 所以在减少大图的内存占用中, Resource 做的非常好

使用Bundle文件

使用 imageWithContentsOfFile 读取

/// BSKDefine.h

// bundle path
#define STBundle_Name @"SafeToolResource.bundle"
#define STBundle_Path [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:STBundle_Name]
#define STBundle [NSBundle bundleWithPath:STBundle_Path]
/// usage

#import "BSKDefine.h"
UIImageView * headerBgImgView = [[UIImageView alloc] init];
headerBgImgView.image = [UIImage imageWithContentsOfFile:[SecKill_BUNDLE pathForResource:@"xxxx" ofType:@"png"]];

对 UIImage 进行扩展,创建 UIImage+BSKResources 类

/// UIImage+BSKResources.h

NS_ASSUME_NONNULL_BEGIN

@interface UIImage (BSKResources)

+ (UIImage *)bskImageNamed:(NSString *)imageName InBundleName:(NSString *)bundleName;

@end

NS_ASSUME_NONNULL_END
/// UIImage+BSKResources.m

#import "UIImage+BSKResources.h"

@implementation UIImage (BSKResources)

+ (UIImage *)bskImageNamed:(NSString *)imageName InBundleName:(NSString *)bundleName
{
  NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundleName];
  NSBundle *resourceBundle = [NSBundle bundleWithPath:resourcePath];
  return [UIImage imageNamed:imageName inBundle:resourceBundle compatibleWithTraitCollection:nil];
}
@end

/// usage

#import "UIImage+BSKResources.h"

UIImageView * headerBgImgView = [[UIImageView alloc] init];
headerBgImgView.image = [UIImage bskImageNamed:@"xxx" InBundleName:@"BSKResources.bundle"]];

Bundle 和 xcassets 区别

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文