Image.xcassets
圖片直接加入工程中作為Resource
讀取方式:創(chuàng)建圖片 Resource 文件夾,直接將圖片加入到工程中,使用如下方式讀取圖片
NSString *path = [NSBundle.mainBundle pathForResource:@"xxx" type:@"png"];UIImage *image = [UIImage imageWithContentsOfFile:path];
特性:在 Resource 的圖片管理方式中, 所有的圖片創(chuàng)建都是通過讀取文件數(shù)據(jù)得到的, 讀取一次文件數(shù)據(jù)就會產生一次 NSData 以及產生一個 UIImage。 當圖片創(chuàng)建好后銷毀對應的 NSData,當 UIImage 的引用計數(shù)器變?yōu)?0 的時候自動銷毀 UIImage,這樣的話就可以保證圖片不會長期地存在在內存中
使用場景:由于這種方法的特性, 所以 Resource 的方法一般用在圖片數(shù)據(jù)很大, 圖片一般不需要多次使用的情況,比如說引導頁背景(圖片全屏)
優(yōu)勢:圖片不會長期保存在內存當中, 所以不會有很多的內存浪費。同時, 大圖一般不會長期使用, 而且大圖占用內存一般比小圖多了好多倍, 所以在減少大圖的內存占用中, 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 進行擴展,創(chuàng)建 UIImage+BSKResources 類
/// UIImage+BSKResources.hNS_ASSUME_NONNULL_BEGIN@interface UIImage (BSKResources)+ (UIImage *)bskImageNamed:(NSString *)imageName InBundleName:(NSString *)bundleName;@endNS_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 區(qū)別
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答