Skip to content

Instantly share code, notes, and snippets.

@nielsbot
Last active December 11, 2015 23:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nielsbot/4678311 to your computer and use it in GitHub Desktop.
Save nielsbot/4678311 to your computer and use it in GitHub Desktop.
Create CGColor from HTML/CSS/Hex color string
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