UIColor+Hex.h
#import <UIKit/UIKit.h>
#define RGBA_COLOR(R, G, B, A) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:A]
#define RGB_COLOR(R,G,B) [UIColor colorWithRed:((R) / 255.0f) green: ((G) / 255.0f) blue:((B) / 255.0f) alpha: 1.0f]
//隨機(jī)生成顏色
#define RandomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))
@interface UIColor (Hex)
// 從十六進(jìn)制字符串獲取顏色智亮,
// color:支持@“#123456”忆某、 @“0X123456”、 @“123456”三種格式
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;
+ (UIColor *)colorWithHexString:(NSString *)color;
//根據(jù)UIColor一個顏色生成一張圖片
+ (UIImage *)imageWithColor:(UIColor *)color;
@end
UIColor+Hex.m
#import "UIColor+Hex.h"
@implementation UIColor (Hex)
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha {
// 刪除字符串中的空格
NSString * colorStr = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([colorStr length] < 6) {
return [UIColor clearColor];
}
// strip 0X if it appears
// 如果是0x開頭的阔蛉,那么截取字符串弃舒,字符串從索引為2的位置開始,一直到末尾
if ([colorStr hasPrefix:@"0X"]) {
colorStr = [colorStr substringFromIndex:2];
}
// 如果是#開頭的状原,那么截取字符串聋呢,字符串從索引為1的位置開始,一直到末尾
if ([colorStr hasPrefix:@"#"]) {
colorStr = [colorStr substringFromIndex:1];
}
// 除去所有開頭字符后 再判斷字符串長度
if ([colorStr length] != 6) {
return [UIColor clearColor];
}
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//red
NSString * redStr = [colorStr substringWithRange:range];
//green
range.location = 2;
NSString * greenStr = [colorStr substringWithRange:range];
//blue
range.location = 4;
NSString * blueStr = [colorStr substringWithRange:range];
// Scan values 將十六進(jìn)制轉(zhuǎn)換成二進(jìn)制
unsigned int r, g, b;
[[NSScanner scannerWithString:redStr] scanHexInt:&r];
[[NSScanner scannerWithString:greenStr] scanHexInt:&g];
[[NSScanner scannerWithString:blueStr] scanHexInt:&b];
return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}
+ (UIColor *)colorWithHexString:(NSString *)color {
return [self colorWithHexString:color alpha:1.0f];
}
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); //寬高 1.0只要有值就夠了
UIGraphicsBeginImageContext(rect.size); //在這個范圍內(nèi)開啟一段上下文
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);//在這段上下文中獲取到顏色UIColor
CGContextFillRect(context, rect);//用這個顏色填充這個上下文
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();//從這段上下文中獲取Image屬性,,,結(jié)束
UIGraphicsEndImageContext();
return image;
}
@end
參考文章:
OC_UIColor 類擴(kuò)展支持十六進(jìn)制
iOS開發(fā)小方法:根據(jù)UIColor一個顏色生成一張圖片
iOS -UIColor隨機(jī)生成顏色的方法