对颜色的认识
颜色是有红色(red)绿色(green)蓝色(blue)组成的。颜色值24位的颜色如:#0X123456。前面两位12表示红色,中间两位34表示绿色,最后两位56表示蓝色。32位的颜色值如:#0X01123456,前面的01表示透明度。后面的和24位的一样。
ios颜色的设置
- 普通色颜色设置(系统方法)
objc
//注意这个r、g、b表示红色、绿色、蓝色,且必须除以255.0。只有这样得到浮点型的值
[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
- 数值类的设置 alpha表示透明度的范围:0~1
####不是字符串形式的十六进制 支持0X123456、0x123456、 两种格式
```objc```
+ (UIColor *)colorWithRGBHex:(UInt32)hex
{
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: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];
}
- 颜色值是NSString的十六进制的值
从十六进制字符串获取颜色 color:支持@“#123456”、 @“0X123456”、@“0x123456”、 @“123456”四种格式
objc
-
(UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
//删除字符串中的空格
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6)
{
return [UIColor clearColor];
}
// strip 0X if it appears
//如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
if ([cString hasPrefix:@"0X"]||[cString hasPrefix:@"0x"])
{
cString = [cString substringFromIndex:2];
}
//如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
if ([cString hasPrefix:@"#"])
{
cString = [cString substringFromIndex:1];
}
if ([cString length] != 6)
{
return [UIColor clearColor];
}// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];// Scan values
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:alpha];
}
代码具体下载地址是:https://github.com/qibingying/iosDevelopInsight/tree/master/%E9%A2%9C%E8%89%B2
网友评论