iOS-组件化加载图片等资源文件

一般组件的核心代码放在Classes目录中,而图片存放于Assets目录下,如图所示,拖动部分图片到Assets中


一、修改Spec(Podfile中未使用use_frameworks!)

修改HFMyTest.podspec资源加载方式

s.resource_bundles = {
  'HFMyTestImg' => ['HFMyTest/Assets/*']
}

HFMyTestImg为显示的图片资源的bundle的名字,在本地会显示为HFMyTestImg.bundle,这个可以自定义,HFMyTest/Assets为图片文件目录
回到HFMyTestExample模块,我们进行一次本地的安装和测试(pod install)

FFMyView中添加如下代码

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        imgView.image = [UIImage imageNamed:@"白富美.png"];
    }
    return self;
}

@end

然后在主控制器FFViewController中调用FFMyView

#import "FFViewController.h"
#import <HFMyTest/FFMyView.h>

@interface FFViewController ()

@end

@implementation FFViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    FFMyView *imgView = [[FFMyView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:imgView];
    imgView.backgroundColor = [UIColor redColor];
}

@end

运行一次项目,发现图片不能正常的显示出来

二、 修改资源加载方式

上面的图片加载方式为

[UIImage imageNamed:@"图片名称"];

在项目中我们打开主包内容


右键显示图片的资源包HFMyTestImg.bundle的包内容就可以看见里面图片资源了


通常如果我们在主工程调用主工程的资源时,可以直接imageName或者[mainbundle pathForResource]读取,但是在用pod进行管理的时候,pod中的资源文件也会变成bundle加入到mainBundle中,但是由于资源文件的bundle并不是mainBundle,所以这种方法是行不通的,关键是要取到资源相关联的bundle

上面图片可以看出图片资源处于HFMyTestimg.bundle包下,所以需要拼接方式关联到该包下

NSURL *bundleURL = [[NSBundle mainBundle]  URLForResource:bundleName withExtension:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];

修改项目代码为

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"HFMyTestImg" withExtension:@"bundle"];
        if (bundleURL) {
            NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
            NSInteger scale = [[UIScreen mainScreen] scale];
            NSString *imgName = [NSString stringWithFormat:@"%@@%zdx.png", @"白富美",scale];
            imgView.image = [UIImage imageWithContentsOfFile:[bundle pathForResource:imgName ofType:nil]];
        }
    }
    return self;
}

@end

上面的图片加载imgName必须使用图片的完整名称,如白富美@2x.png

或者下面的代码

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        NSString *imgName = [NSString stringWithFormat:@"%@/%@", @"HFMyTestImg.bundle",@"白富美"];
        imgView.image = [UIImage imageNamed:imgName];
    }
    return self;
}

@end

接下来运行项目就可以看见图片了


还看见网上一种加载方式

NSBundle *currentBundle = [NSBundle bundleForClass:[self class]];
//图片名称要写全称
NSString *patch = [currentBundle pathForResource:@"Group.png" ofType:nil inDirectory:@"wgPersonInfoKit.bundle"];
_imgView.image = [UIImage imageWithContentsOfFile:patch];

因为修改的地方会很多,所以把这个方法抽出来:

新建一个UIImage的分类

#import <UIKit/UIKit.h>

@interface UIImage (wgBundle)

+ (instancetype)wg_imgWithName:(NSString *)name bundle:(NSString *)bundleName targetClass:(Class)targetClass;

@end
#import "UIImage+wgBundle.h"

@implementation UIImage (wgBundle)

+ (instancetype)wg_imgWithName:(NSString *)name bundle:(NSString *)bundleName targetClass:(Class)targetClass{
    NSInteger scale = [[UIScreen mainScreen] scale];
    NSBundle *curB = [NSBundle bundleForClass:targetClass];
    NSString *imgName = [NSString stringWithFormat:@"%@@%zdx.png", name,scale];
    NSString *dir = [NSString stringWithFormat:@"%@.bundle",bundleName];
    NSString *path = [curB pathForResource:imgName ofType:nil inDirectory:dir];
    return path?[UIImage imageWithContentsOfFile:path]:nil;
}

@end

在使用的地方

_imgView.image = [UIImage wg_imgWithName:@"Group" bundle:@"wgPersonInfoKit" targetClass:[self class]];

上面资源加载方式为
s.resource_bundles = {
  'HFMyTestImg' => ['HFMyTest/Assets/*']
}
资源加载方式还有另一种
s.resources = ['HFMyTest/Assets/*']

这两种的区别在于s.resource_bundles会自动创建HFMyTestImg.bundle包(这个HFMyTestImg自己自定义的),而s.resources不会创建bundle,文件会直接放到目录下

三、采用s.resources加载资源

s.resources = ['HFMyTest/Assets/*']

pod install重新加载项目,然后采用上面的方式显示包内容

删除掉之前的缓存记录,然后重新运行下程序,在进入到显示包内容里面

会发现包里面的内容时这样的

和上面不同的是上面的图片资源全部被自动打包到HFMyTestImg.bundle中,这个里面的图片资源没有打包成bundle,而是直接显示在主包mainBundle中的,这种方式加载图片时可以直接采用imageNamed,同时也不需要写出完整的图片名字

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        imgView.image = [UIImage imageNamed:@"白富美"];
    }
    return self;
}

@end

需要注意的点

OC工程的Podfile一般是不使用use_frameworks!的,swift和自己创建的lib库是默认有的,关于这两点的差异,如果Podfile不使用use_frameworks!pod里的资源文件会被打成bundle放在mainBundle下面,如果使用的话会被放到mainBundleFrameworks文件夹下的,下面进行详细说明下

上面的Podfile采用的是
#use_frameworks!

target 'HFMyTest_Example' do
  pod 'HFMyTest', :path => '../'

  target 'HFMyTest_Tests' do
    inherit! :search_paths

  end
end

并没有采用use_frameworks!
采用use_frameworks!将在下面进行说明

四、采用use_frameworks!

  1. 使用resource_bundles
    修改Podfile文件为
use_frameworks!

target 'HFMyTest_Example' do
  pod 'HFMyTest', :path => '../'

  target 'HFMyTest_Tests' do
    inherit! :search_paths

  end
end
`HFMyTest.podspec`文件为

回到项目主目录

cd /Users/hf/MyTest/HFMyTest/Example
pod install

更新完成后重新打开HFMyTest.xcworkspace,和之前操作一样的方式删除掉缓存文件,也可以采用下面方式清除缓存

运行程序,然后如上方式一样打开文件包内容,会发现图片资源的位置改变了

图片资源在Frameworks下的HFMyTest.framework下的HFMyTestImg.bundle包中
所以这时候加载图片已经不再mainBundle中了,需要指定带现在的图片资源目录中

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        //到指定目录
        NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"Frameworks" withExtension:nil];
        bundleURL = [bundleURL URLByAppendingPathComponent:@"HFMyTest"];
        bundleURL = [bundleURL URLByAppendingPathExtension:@"framework"];
        if (bundleURL) {
            NSBundle *imgBundle = [NSBundle bundleWithURL:bundleURL];
            bundleURL = [imgBundle URLForResource:@"HFMyTestImg" withExtension:@"bundle"];
            if (bundleURL) {
                NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
                NSInteger scale = [[UIScreen mainScreen] scale];
                NSString *imgName = [NSString stringWithFormat:@"%@@%zdx.png", @"白富美",scale];
                imgView.image = [UIImage imageWithContentsOfFile:[bundle pathForResource:imgName ofType:nil]];
            }
        }
    }
    return self;
}

@end
  1. 使用resources

首先pod install程序,重新打开HFMyTest.xcworkspace,然后清除缓存(快捷键shift+command+k),运行程序,打开查看程序包内容

其实相对于resource_bundles少了个打包的bundleresource_bundles会自动创建一个bundle

修改FFMyView.m的代码为

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        //到指定目录
        NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"Frameworks" withExtension:nil];
        bundleURL = [bundleURL URLByAppendingPathComponent:@"HFMyTest"];
        bundleURL = [bundleURL URLByAppendingPathExtension:@"framework"];
        if (bundleURL) {
            NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
            NSInteger scale = [[UIScreen mainScreen] scale];
            NSString *imgName = [NSString stringWithFormat:@"%@@%zdx.png", @"白富美",scale];
            imgView.image = [UIImage imageWithContentsOfFile:[bundle pathForResource:imgName ofType:nil]];
        }
    }
    return self;
}

@end

就可以正常的展示图片了

正常情况下,对于采用了resources加载资源的,可以手动创建bundle用于存放图片资源

五、手动创建bundlePodfile中未使用use_frameworks!

右键新建文件夹


重命名改文件夹名字为MyImg.bundle

右键MyImg.bundle显示包内容,将之前的图片资源copy到里面去

cd /Users/hf/MyTest/HFMyTest/Example
pod install

重新打开HFMyTest.xcworkspace,发现pod中的目录变化了

清除缓存(shift+command+k),然后运行程序,再去打开包的内容


发现了图片在mainBundleMyImg.bundle包下,这种形式相对于resource_bundles形式来说,它把图片资源同样打包了,但是在本地资源中,它显示形式是MyImg.bundle,图片全在bundle里面,而resource_bundles在本地显示没有bundle,直接显示的是图片的资源,采用下面的代码就可以调用

#import "FFMyView.h"

@implementation FFMyView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        [self addSubview:imgView];
        imgView.backgroundColor = [UIColor yellowColor];
        NSString *imgName = [NSString stringWithFormat:@"%@/%@",@"MyImg.bundle",@"白富美"];
        imgView.image = [UIImage imageNamed:imgName];
    }
    return self;
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容