Search code examples
iosuikituicolor

How to convert UIColor to Hexadecimal (web color text string)?


Is there an easy way to convert UIColor to a hexadecimal value ?
Or do we have to get the RGB components with CGColorGetComponents and then work it out from there?

e.g CGColorGetComponents(color.CGColor)[0] * 256 ?


Solution

  • I would consider using Erica Sadun's UIColor category. It includes a lot of functionality for free, including hex representations. It's pretty easy to use, just add it to whatever class header you're using it in or, add it to the pre-compiled header for ultimate flexibility. If you're adding to the pre-compiled header, do so similar to something like this:

    #ifdef __OBJC__
        #import <Foundation/Foundation.h>
        #import <UIKit/UIKit.h>
        #import "UIColor-Expanded.h"
    #endif
    

    Then You can use it like so NSLog(@"%@", [myColor hexStringFromColor]);

    GitHub link to the UIColor category: https://github.com/erica/uicolor-utilities

    ArsTechnica article about it: http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars