開發時,使用顏色的時候都是用的RGB顏色,但是UI設計師提供的顏色值一般都是十六進制的,轉換起來非常麻煩。
我對UIColor做了擴展,可以直接使用十六進制格式的顏色。
一、主要步驟
1.對UIColor使用Category(類別)
- 此處只需要對UIColor擴充方法,并不需要擴充成員變量和屬性,所以只需要使用Category,不需要使用Extension。
- Category最顯著的特征就是小括號中有名字,而且文件名中有“+”,如:UIColor+Tool.h和UIColor+Tool.m
setp1.png
setp2.png
2.使用十六進制顏色的類方法
(1)UIColor+Tool.h中
#import <UIKit/UIKit.h>
@interface UIColor (Tool)
/**
* 16進制轉換成UIColor
*
* @param hex
*
* @return UIColor
*/
+ (UIColor *)colorWithRGBHex:(UInt32)hex;
/**
* 16進制轉換成UIColor,帶透明度
*
* @param hex 十六進制顏色 eg. 0x8b8b8e
* @param alpha 透明度 取值 0-1.0
*
* @return UIColor
*/
+ (UIColor *)colorWithRGBHex:(UInt32)hex alpha:(CGFloat)alpha;
@end
(2)UIColor+Tool.m中
#import "UIColor+Tool.h"
@implementation UIColor (Tool)
//16進制轉換成UIColor
+ (UIColor *)colorWithRGBHex:(UInt32)hex {
return [UIColor colorWithRGBHex:hex alpha:1.0f];
}
+ (UIColor *)colorWithRGBHex:(UInt32)hex alpha:(CGFloat)alpha {
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;
return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:alpha];
}
@end
二、使用
1.
#import "UIColor+Tool.h"
2.
UIColor *backgroundColor = [UIColor colorWithRGBHex:0xF83838];
UIColor *viewColor = [UIColor colorWithRGBHex:0xF83838 alpha:0.8f];
三、更加簡單粗暴的方法
直接用宏定義,我更喜歡使用宏定義的方式
//十六進制色值
#define kUIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//十六進制色值,有透明度
#define kUIColorFromRGBWithTransparent(rgbValue,transparentValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:transparentValue]