颜色管理工具
1、单例管理
2、RGB管理
3、十六进制(#FFFFFF,0xFFFFFF)管理
4、缓存机制(色值进行了缓存,若存在则直接从缓存池取)
5、内存释放机制(当颜色值存储大于30(可自己设置)个时或内存警告时,会释放缓存池)
工程目录
代码
ColorValues 色值宏类
#ifndef ColorValues_h
#define ColorValues_h
#import "ComColorManager.h"
#pragma mark - 颜色方法区
//RGB颜色方法
#define COLOR_RGB(r,g,b) [UIColor colorWithRed:((r)/255.0) green:((g)/255.0) blue:((b)/255.0) alpha:1.0]
#define COLOR_RGBA(r,g,b,a) [UIColor colorWithRed:((r)/255.0) green:((g)/255.0) blue:((b)/255.0) alpha:(a)]
// 颜色(单利)
#define kComColorManager [ComColorManager defaultManager]
//辅助颜色
#define kTitleColor [kComColorManager getColorWithHexString:@"#333333"]
// e.g. HEXCOLOR(0xCECECE);
#define HEXCOLOR(rgbValue) [ComColorManager colorWithHex:rgbValue alpha:1.f]
// e.g. HEXCOLORA(0xCECECE, 0.8);
#define HEXCOLORA(rgbValue,a) [ComColorManager colorWithHex:rgbValue alpha:a]
#define Color_BaseBgView HEXCOLOR(0xe5e5e);
#endif
ComColorManager管理类
@interface ComColorManager : NSObject
+(instancetype)defaultManager;
/**
* 获取UIColor,优先在内存中获取
*
* @param hexColor 如0xffffff 或 #ffffff
*
* @return UIColor
*/
- (UIColor*)getColorWithHexString:(NSString*)hexColor;
/**
* 通过十六进制格式获取UIColor
*
* @param hexColor 如0xffffff 或 #ffffff
*
* @return UIColor 这个方法不会从内存中读取
*/
+ (UIColor*)colorWithHexString:(NSString *)hexColor;
/**
* 获取UIColor,优先在内存中获取
*
* @param hexColor 如0xffffff 或 #ffffff alpha = 0~1.0
*
* @return UIColor
*/
+ (UIColor*)colorWithHex:(NSInteger)hex alpha:(CGFloat)alpha;
@end
- (void)dealloc {
[[NSNotificationCenterdefaultCenter] removeObserver:self];
}
+ (instancetype)defaultManager {
staticdispatch_once_t once;
static ComColorManager * __singleton__;
dispatch_once( &once, ^{
__singleton__ = [[ComColorManager alloc] init];
});
return __singleton__;
}
- (id)init {
self = [superinit];
if (self) {
self.colorsDict = [NSMutableDictionarydictionary];
[[NSNotificationCenterdefaultCenter] addObserver:self
selector:@selector(onRecvMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
- (void)onRecvMemoryWarning {
[self.colorsDictremoveAllObjects];
}
- (UIColor*)getColorWithHexString:(NSString*)hexColor {
if (!hexColor) {
if (self.colorsDict[@"clearColor"]) {
return self.colorsDict[@"clearColor"];
}
UIColor *color = [[selfclass] colorWithHexString:@"clearColor"];
[self.colorsDictsetObject:color forKey:@"clearColor"];
return color;
}
//如果保持有
if (self.colorsDict[hexColor]) {
return self.colorsDict[hexColor];
}
if ([self.colorsDictcount]>30) {
[self.colorsDictremoveAllObjects];
}
UIColor *color = [[selfclass] colorWithHexString:hexColor];
[self.colorsDictsetObject:color forKey:hexColor];
return color;
}