UIColor值是由4个0~1的值组成(Red,Green,Blue和Alpha值),而颜色的十六进制值(hex值)是一个十六进制数。这份代码是这两个值直接的互相转换。
+ (UIColor*) colorWithHex:(NSInteger)hexValue alpha:(CGFloat)alphaValue { return [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:alphaValue]; } + (UIColor*) colorWithHex:(NSInteger)hexValue { return [UIColor colorWithHex:hexValue alpha:1.0]; } + (NSString *) hexFromUIColor: (UIColor*) color { if (CGColorGetNumberOfComponents(color.CGColor) < 4) { const CGFloat *components = CGColorGetComponents(color.CGColor); color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]]; } if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) { return [NSString stringWithFormat:@"#FFFFFF"]; } return [NSString stringWithFormat:@"#XXX", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)]; }
时间: 2024-10-12 02:20:39