Skip to content

Instantly share code, notes, and snippets.

@zhangwc
Created August 28, 2013 14:14
Show Gist options
  • Save zhangwc/6366479 to your computer and use it in GitHub Desktop.
Save zhangwc/6366479 to your computer and use it in GitHub Desktop.
// 如hex为0xEEEEEE
+ (UIColor *) colorWithHex:(int)hex {
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0
                          green:((float)((hex & 0xFF00) >> 8))/255.0
                            blue:((float)(hex & 0xFF))/255.0 alpha:1.0];
}
// hex为#EEEEEE
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert {
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor whiteColor];
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString 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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment