iOS: Create UIColor Object From A Hex String (NSString)


If you need to convert a hex value stored in an NSString into a UIColor object, you’ve come to the right place.
As an example, assume you have the value @”0A5CEA” and need a UIColor object that represents the value of the string. With the code below, creating the UIColor object is as easy as:
UIColor *color = [self getUIColorObjectFromHexString:@"0A5CEA" alpha:.9];
Notice that I also provide a parameter to set the alpha value.
The code also supports hex values in the format @”0x0A5CEA” or @”#0A5CEA” (where the later is common in web development).
Convert Hex String To Integer
The first step is to convert the hex value stored as string into an integer. I covered the specifics of this in the post Convert Hex Value Stored As NSString To Integer.
The code is duplicated here:
- (unsigned int)intFromHexString:(NSString *)hexStr
{
  unsigned int hexInt = 0;
 
  // Create scanner
  NSScanner *scanner = [NSScanner scannerWithString:hexStr];
 
  // Tell scanner to skip the # character
  [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
 
  // Scan hex value
  [scanner scanHexInt:&hexInt];
 
  return hexInt;
}
The code below uses the integer value of the hex string to create a UIColor object by doing a bitwise ‘&’ operation to isolate the various color attributes and divide each by 255 to get the float value:
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
  // Convert hex string to an integer
  unsigned int hexint = [self intFromHexString:hexStr];
 
  // Create color object, specifying alpha as well
  UIColor *color =
    [UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
    green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
    blue:((CGFloat) (hexint & 0xFF))/255
    alpha:alpha];
 
  return color;
}
The code below shows a few iterations:
NSString *hexStr1 = @"123ABC";
NSString *hexStr2 = @"#123ABC";
NSString *hexStr3 = @"0x123ABC";
 
UIColor *color1 = [self getUIColorObjectFromHexString:hexStr1 alpha:.9];
NSLog(@"UIColor: %@", color1);
 
UIColor *color2 = [self getUIColorObjectFromHexString:hexStr2 alpha:.9];
NSLog(@"UIColor: %@", color2);
 
UIColor *color3 = [self getUIColorObjectFromHexString:hexStr3 alpha:.9];
NSLog(@"UIColor: %@", color3);
As expected, the output for each hex string is the same:
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
iOS: Create UIColor Object From A Hex String (NSString) iOS: Create UIColor Object From A Hex String (NSString) Reviewed by Unknown on 12:06 Rating: 5

No hay comentarios:

Con la tecnología de Blogger.