在開(kāi)發(fā)中常常會(huì)遇到換膚的情況,如果每次都用一個(gè)判斷語(yǔ)句去修改圖片會(huì)相當(dāng)?shù)穆闊瑸榱斯ぷ餍枰疫M(jìn)行了深入研究找到一種方法嘱腥。
1、創(chuàng)建兩個(gè)bundle來(lái)存放資源文件德谅,里面包含plist文件和圖片
把所需要的圖片放進(jìn)去爹橱,plist文件中寫(xiě)對(duì)應(yīng)的顏色
2、寫(xiě)一個(gè)配置文件來(lái)集中處理圖片和顏色
#import "DDSkin.h"
#define SkinColor @"DDDkinColor"
@implementation DDSkin
static NSString *_color;
+ (void)initialize {
// 開(kāi)始窄做,從沙盒中取之前存儲(chǔ)的皮膚顏色
_color = [[NSUserDefaults standardUserDefaults] objectForKey:SkinColor];
if (_color == nil) { // 之前沒(méi)有存儲(chǔ),取出為空慰技,默認(rèn)為藍(lán)色
_color = @"blue";
}
}
/**
*? 通過(guò)該方法可以設(shè)置皮膚的顏色
*
*? @param color 皮膚的顏色
*/
+ (void)setSkinColor:(NSString *)color {
_color = color;
// 將用戶(hù)設(shè)置的皮膚顏色進(jìn)行保存
[[NSUserDefaults standardUserDefaults] setObject:color forKey:SkinColor];
[[NSUserDefaults standardUserDefaults] synchronize];
}
/**
*? 通過(guò)該方法,可以返回想要的UIImage
*
*? @param name 圖片的名稱(chēng)
*
*? @return 當(dāng)前皮膚對(duì)應(yīng)的UIImage
*/
+ (UIImage *)ddSkinWithImageName:(NSString *)name {
NSString *path = [[NSBundle mainBundle] pathForResource:_color ofType:@"bundle"];
NSString *imagePath = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",name]];
return [[UIImage alloc] initWithContentsOfFile:imagePath];
}
/**
*? 返回當(dāng)前皮膚的Label背景顏色
*
*? @return 當(dāng)前的背景顏色
*/
+ (UIColor *)ddSkinWithColorName:(NSString *)name {
// 1.獲取文件夾位置
NSString *path = [[NSBundle mainBundle] pathForResource:_color ofType:@"bundle"];
//獲取文件位置
NSString *plistPath = [path stringByAppendingString:@"/color.plist"];
//讀取plist當(dāng)中的數(shù)據(jù)
NSDictionary *colorDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
//將字典當(dāng)中的值取出
NSString *bgStr = [colorDict objectForKey:name];
//將顏色的字符串截取
NSArray *bgArray = [bgStr componentsSeparatedByString:@","];
//取出顏色的r,g,b數(shù)值
CGFloat red = [bgArray[0] floatValue];
CGFloat green = [bgArray[1] floatValue];
CGFloat blue = [bgArray[2] floatValue];
//返回當(dāng)前皮膚的顏色
return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
}
@end
3椭盏、調(diào)用的方法
- (void)viewDidLoad {
[super viewDidLoad];
[self.ragBurron addTarget:self action:@selector(ragButtonTouch) forControlEvents:UIControlEventTouchUpInside];
[self.blueButton addTarget:self action:@selector(blueButtonTouch) forControlEvents:UIControlEventTouchUpInside];
self.blackView.backgroundColor = [DDSkin ddSkinWithColorName:@"color"];
self.imageView.image = [DDSkin ddSkinWithImageName:@"xianxian.jpg"];
}
- (void)ragButtonTouch {
[DDSkin setSkinColor:@"rad"];
self.blackView.backgroundColor = [DDSkin ddSkinWithColorName:@"color"];
self.imageView.image = [DDSkin ddSkinWithImageName:@"xianxian.jpg"];
}
- (void)blueButtonTouch {
[DDSkin setSkinColor:@"blue"];
self.blackView.backgroundColor = [DDSkin ddSkinWithColorName:@"color"];
self.imageView.image = [DDSkin ddSkinWithImageName:@"xianxian.jpg"];
}