在iOS开发中,我们常常会在界面色调搭配的时候选色比较麻烦,因为系统大多提供给我们的是一些基本颜色,还有就是取色器强行配色。但实际我们所需要的更多色调都有具体的十六进制表示,接下来我们就看看十六进制颜色与我们经常使用的RGB值之间的转换
1.由于文中经常用到,所以我直接在一个类中封装一个HEX转化方法,以便后面方便使用:
.h文件:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface HexColor : NSObject
/*在.h中进行申明方法*/
+ (UIColor *)colorWithHexString:(NSString *)color;
@end
.m文件:
#import "HexColor.h"
@implementation HexColor
#pragma mark -- 16进制Color转换
+ (UIColor *)colorWithHexString:(NSString *)color
{
NSString *cString = [[colorstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]]uppercaseString];
if ([cStringlength] < 6) {
return [UIColorclearColor];
}
if ([cStringhasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cStringhasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cStringlength] != 6)
return [UIColorclearColor];
NSRange range;
range.location =0;
range.length =2;
NSString *rString = [cStringsubstringWithRange:range];
range.location =2;
NSString *gString = [cStringsubstringWithRange:range];
range.location =4;
NSString *bString = [cStringsubstringWithRange:range];
unsignedint r, g, b;
[[NSScannerscannerWithString:rString] scanHexInt:&r];
[[NSScannerscannerWithString:gString] scanHexInt:&g];
[[NSScannerscannerWithString:bString] scanHexInt:&b];
return [UIColorcolorWithRed:((float) r /255.0f) green:((float) g /255.0f) blue:((float) b /255.0f) alpha:1.0f];
}
@end
2.例如在某个颜色设置中调用:
self.view.backgroundColor = [HexColorcolorWithHexString:@"a1f1f2"];
PS:这样就可以方便我们随意搭配各种颜色了。