在开发中,UI给出的颜色值有时候是十六进制的,有时候给出的是RGB(255,255,255)这样的形式的,而iOS系统提供的方法中并没有直接传递这两种值返回UIColor对象的,这里自己封装了一个以便使用。
UIColor+LMColor.h
#import <UIKit/UIKit.h>
@interface UIColor(LMColor)
/**
* 获取透明度为1的随机颜色
*
* @return 随机获得的UIColor对象
*/
+ (UIColor *)randColor;
/**
* 将16进制的颜色值转换成UIColor对象
*
* @param colorStr 16进制表示的颜色(0xc36000,0Xc36000,#c36000或者c36000格式都支持)
* @param alpha 透明度
*
* @return 转换过后的UIColor对象
*/
+ (UIColor *)colorWithHexString:(NSString *)colorStr alpha:(CGFloat)alpha;
/**
* 返回(168,57,23)表示形式的UIColor
*
* @param r 红,0~255
* @param g 绿,0~255
* @param b 蓝,0~255
* @param a 透明度,0~100
*
* @return 转换过后UIColor对象
*/
+(UIColor *)colorWithR:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a;
@end
UIColor+LMColor.m
#import "UIColor+LMColor.h"
@implementation UIColor(LMColor)
+ (UIColor *)randColor {
CGFloat r = arc4random_uniform(256);
CGFloat g = arc4random_uniform(256);
CGFloat b = arc4random_uniform(256);
return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1];
}
+(UIColor *)colorWithR:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a{
return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a/100.0f];
}
+ (UIColor *)colorWithHexString:(NSString *)colorStr alpha:(CGFloat)alpha {
//移除前缀
if ([colorStr hasPrefix:@"0X"] || [colorStr hasPrefix:@"0x"]) {
colorStr = [colorStr substringFromIndex:2];
}
if ([colorStr hasPrefix:@"#"]) {
colorStr = [colorStr substringFromIndex:1];
}
//判断长度
if (colorStr.length != 6) {
return [UIColor clearColor];
}
//提取值
NSRange range;
range.length = 2;
//r
range.location = 0;
NSString *rStr = [colorStr substringWithRange:range];
//g
range.location = 2;
NSString *gStr = [colorStr substringWithRange:range];
//b
range.location = 4;
NSString *bStr = [colorStr substringWithRange:range];
//转换值
unsigned int r, g, b;
[[NSScanner scannerWithString:rStr] scanHexInt:&r];
[[NSScanner scannerWithString:gStr] scanHexInt:&g];
[[NSScanner scannerWithString:bStr] scanHexInt:&b];
return [UIColor colorWithRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:alpha];
}
@end