Last active
December 11, 2015 23:39
-
-
Save nielsbot/4678311 to your computer and use it in GitHub Desktop.
Create CGColor from HTML/CSS/Hex color string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static CGColorRef CGColorCreateWithCSSColor( NSString * string ) | |
{ | |
union { | |
struct { | |
#if LITTLE_ENDIAN | |
uint8 alpha ; | |
uint8 blue ; | |
uint8 green ; | |
uint8 red ; | |
#else | |
uint8 red ; | |
uint8 green ; | |
uint8 blue ; | |
uint8 alpha ; | |
#endif | |
} each ; | |
uint32 rgba ; | |
} color = { 0 } ; | |
color.each.alpha = 0xFF ; | |
const char * cString = [ string cStringUsingEncoding:NSUTF8StringEncoding ] ; | |
const char * p = cString ; | |
if ( *p == '#' ) { ++p ; } | |
int32_t shift = 28 ; | |
while( *p != 0 ) | |
{ | |
uint8 value = *p & 0xf ; | |
if ( *p > 0x41 ) { value += 9 ; } | |
color.rgba |= ( value << shift ) ; | |
shift -= 4 ; | |
++p ; | |
} | |
CGColorRef result = CGColorCreateGenericRGB( (CGFloat)color.each.red / 255.0f, (CGFloat)color.each.green / 255.0f, (CGFloat)color.each.blue / 255.0f, (CGFloat)color.each.alpha / 255.0f ) ; | |
return result ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment