今天开发中需要将UIColor转为十六进制字符串,记录下修改代码
UIColor *color = [UIColor blueColor]; const CGFloat* components = CGColorGetComponents(color.CGColor); NSString *alpha = [self getHexByDecimal:CGColorGetAlpha(color.CGColor)*255.0]; NSString *red = [self getHexByDecimal:components[0]*255.0]; NSString *green = [self getHexByDecimal:components[1]*255.0]; NSString *blue = [self getHexByDecimal:components[2]*255.0]; NSSTring colorStr = [NSString stringWithFormat:@"#%@%@%@%@", alpha, red, green, blue]; /** 十进制转十六进制*/ + (NSString *)getHexByDecimal:(NSInteger)decimal { NSString *hex =@""; NSString *letter; NSInteger number; for (int i = 0; i<9; i++) { number = decimal % 16; decimal = decimal / 16; switch (number) { case 10: letter =@"A"; break; case 11: letter =@"B"; break; case 12: letter =@"C"; break; case 13: letter =@"D"; break; case 14: letter =@"E"; break; case 15: letter =@"F"; break; default: letter = [NSString stringWithFormat:@"%ld", number]; } hex = [letter stringByAppendingString:hex]; if (decimal == 0) { break; } } return hex; }