十六进制颜色转RGB颜色(含#开头)

在做iOS开发的时候,会给控件添加颜色,一般都是RGB色值。如下

self.view.backgroundColor = [UIColor colorWithRed:235/255.0f green:236/255.0f blue:241/255.0f alpha:1];

美工大多数给的颜色往往都是十六进制的颜色。如:#784679这样 ,也会有 0Xe5e589 这样的,当然有时候美工也会给色值加色块(效果图其实都有,没必要给色块) 并且公司对这个不太看重的话,技术为了方便就可以直接用吸管在色块或者效果图吸取了,但是这样会有偏差,这样不推荐。你明白的。
对此写了两个方法,一个为宏,一个为封装。

先说为宏的方法:

define UIColorFromRGB(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]
用法:如 UIColorFromRGB(0Xe5e589)时如果使用这个宏来进行 # 开头色值,则需要把 # 写成0x,如 #784679 写成 0x784679。 这个我试了试,没有看出来偏差在哪(仅为看),但是是否没有一点偏差,就没有测试了。
另一个封装的:

首先导入头文件 #import “UIColor+ColorValue.h”

UIColor+ColorValue.h 文件中
import@interface UIColor (ColorValue)
+(UIColor *) colorWithRGBString: (NSString *)color;
@end
UIColor+ColorValue.m文件中

import "UIColor+ColorChange.h"
@implementation UIColor (ColorChange)

+(UIColor *) colorWithRGBString: (NSString *)color
{
NSString *RGBString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

if ([RGBString length] < 6) {
return [UIColor clearColor];
}

// 判断前缀为 0x 还是 #
if ([RGBString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([RGBString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([RGBString length] != 6)
return [UIColor clearColor];
// 六位数值中找到RGB对应位数并转换
NSRange range;
range.location = 0;
range.length = 2;

//取R、G、B
NSString *rString = [RGBString substringWithRange:range];
range.location = 2;
NSString *gString = [RGBString substringWithRange:range];
range.location = 4;
NSString *bString = [RGBString substringWithRange:range];
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
@end
调用方法:self.view.backgroundColor = [UIColor colorWithRGBString:@"#784679"]  或者  [UIColor colorWithRGBString:@"0x784679"]。
这个方法就不存在是否 0x 开头还是 # 开头了。

今天突然感觉到比较闲,刚好顺便自己写的demo中有这个,顺便写出来。后面会慢慢整理一些平时开发中会经常用到的方法并写出来,供各位参考。如有发现这篇文章有不足或错误之处请指出来并共同探讨。有问题请留言。谢谢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值