Tuesday, 5 July 2011

Using RGB and Hex color with UIKit

UIKit on iOS provides a UIColor class for managing and using colors in your application. Most developer's are however used to RGB or Hex color notation when using colors. Your color palettes are likely in one of these formats. If you use tools like Pixie on Windows or DigitalColor Meter on OS X you are also using RGB and Hex colors. The nearest method UIColor provides for these are initWithRed:green:blue:alpha: and colorWithRed:green:blue:alpha:. The problem is though these methods take float values in the range from 0.0 to 1.0. Converting RGB and Hex colors to this format is discussed below with examples. It's a good idea to roll your own helper methods to make it easier for you to use your existing color palettes. You could even add an extension method to NSString.

Converting RGB color is simple. Each component in RGB (i.e. red, green and blue) is a color from 0 to 255 (i.e. one byte each). Thus to convert these for use with UIColor we need to map colors in the 0 to 255 range to colors in the 0.0 to 1.0 range, in other words divide by 255.0. An example shows how to do this in code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
    
    // Converting RGBA color for use with UIColor
    UIColor *colorFromRgba = [UIColor colorWithRed:23/255.0f green:45/255.0f blue:145/255.0f alpha:1];
    NSLog(@"converted rgba color is: %@", colorFromRgba);
                             
    [self.window makeKeyAndVisible];
    
    return YES;
}

Using colorWithRed:green:blue:alpha: gives you an auto-released UIColor object. If you use initWithRed:green:blue:alpha: then you are responsible for releasing the object once you are done.

The converted color is
[Session started at 2011-07-05 18:55:21 +0400.]
2011-07-05 18:55:22.455 RGBHexUIColor[301:207] converted rgba color is: UIDeviceRGBColorSpace 0.0901961 0.176471 0.568627 1

Converting from Hex colors is slightly more involved. You could for example first parse your hex string and convert it to RGB byte color and then divide each component by 255.0 as discussed above. You can also use bit masks to separate your hex string components. An excellent discussion is available here.

No comments:

Post a Comment