最近公司在做组件化,在处理图片的时候,遇到一些问题,所以记录一下!组件化图片有两种处理方式,第一种是直接创建一个.bundle文件夹,(直接创建一个空文件夹,改名.bundle,然后将图片拖进去,但是这样有不好的地方是,没法适配2x,3X图片)
podspec文件里设置
s.resource_bundles = {
'MyOrderModule' => ['MyOrderModule/Assets/MyOrderModule.bundle']
}
这样会有两层bundle,因为外层就会生成一个bundle
+(UIImage*)getImageWithImageName:(NSString *)imageNamebundle:(NSString*)bundleNametargetClass:(Class)targetClass{
NSIntegerscale = [[UIScreenmainScreen] scale];
NSBundle*bundle = [NSBundlebundleForClass:targetClass];
NSURL*url = [bundleURLForResource:bundleNamewithExtension:@"bundle"];
NSBundle*targetBundle = [NSBundlebundleWithURL:url];
NSString*imgName = [NSStringstringWithFormat:@"%@@%zdx.png",imageName,scale];
UIImage *image = [UIImage imageNamed:imgName inBundle:targetBundle compatibleWithTraitCollection:nil];
return (image)? (image):(([UIImage imageNamed:imgName inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil])?([UIImage imageNamed:imgName inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil]):([UIImage new]));
}
调用的地方使用
UIImage *iamage = [self getImageWithImageName:@"aaa" bundle:@"'MyOrderModule.bundle/MyOrderModule" targetClass:[self class]];
第一个是podspec,前面写的bundle名字 后面的是工程里放图片的bundle名字 targetClass 名字一定要和bundle在同一个组件内,否则会取不到图片
2.第二种方式是Assets文件夹里直接放入Assets.xcassets(自己创建一个Assets,随便起名字)
修改.podspec文件如下:
s.resource_bundles = {
'MyOrderModule' => ['MyOrderModule/Assets/Assets.xcassets']
}
然后pod install
就会看到多了一个Resources文件夹,里面放着Assets文件
- (UIImage*)getImageWithImageName:(NSString*)imageNamebundleName:(NSString*)bundleNametargetClass:(Class)targetClass{
NSBundle*bundle = [NSBundlebundleForClass:targetClass];
NSURL*url = [bundleURLForResource:bundleNamewithExtension:@"bundle"];
NSBundle*targetBundle = [NSBundlebundleWithURL:url];
UIImage *image = [UIImage imageNamed:imageName inBundle:targetBundle compatibleWithTraitCollection:nil];
return image?image:[UIImage imageNamed:imageName inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
}
外面使用
UIImage *iamage = [self getImageWithImageName:@"aaa" bundle:@"'MyOrderModule" targetClass:[self class]];
这个是只会生成一个bundle,就是podspec里面设置的那个bundle
网友评论