How can I create a UIColor
from a hexadecimal string format, such as #00FF00
?
I ended up creating a category for UIColor
that I can just reuse in my other projects, and added this function:
+ (UIColor *)colorFromHex:(unsigned long)hex
{
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0
green:((float)((hex & 0xFF00) >> 8))/255.0
blue:((float)(hex & 0xFF))/255.0
alpha:1.0];
}
The usage goes like:
UIColor *customRedColor = [UIColor colorFromHex:0x990000];
This is far faster than passing on a string and converting it to a number then shifting the bits.
You can also import the category from inside your .pch
file so you can easily use colorFromHex
everywhere in your app like it's built-in to UIColor
:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
// Your other stuff here...
#import "UIColor+HexColor.h"
#endif
Another version with alpha
#define UIColorFromRGBA(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF000000) >> 24))/255.0 green:((float)((rgbValue & 0xFF0000) >> 16))/255.0 blue:((float)((rgbValue & 0xFF00) >> 8 ))/255.0 alpha:((float)((rgbValue & 0xFF))/255.0)]
Here's a Swift 1.2
version written as an extension to UIColor
. This allows you to do
let redColor = UIColor(hex: "#FF0000")
Which I feel is the most natural way of doing it.
extension UIColor {
// Initialiser for strings of format '#_RED_GREEN_BLUE_'
convenience init(hex: String) {
let redRange = Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(3))
let greenRange = Range<String.Index>(start: hex.startIndex.advancedBy(3), end: hex.startIndex.advancedBy(5))
let blueRange = Range<String.Index>(start: hex.startIndex.advancedBy(5), end: hex.startIndex.advancedBy(7))
var red : UInt32 = 0
var green : UInt32 = 0
var blue : UInt32 = 0
NSScanner(string: hex.substringWithRange(redRange)).scanHexInt(&red)
NSScanner(string: hex.substringWithRange(greenRange)).scanHexInt(&green)
NSScanner(string: hex.substringWithRange(blueRange)).scanHexInt(&blue)
self.init(
red: CGFloat(red) / 255,
green: CGFloat(green) / 255,
blue: CGFloat(blue) / 255,
alpha: 1
)
}
}
There's a nice post on how to tackle the OP's question of extracting a UIColor
from a hex string. The solution presented below is different from others because it supports string values that may include '0x' or '#' prefixed to the hex string representation... (see usage)
Here's the main bit...
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create a 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;
}
Helper method...
- (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;
}
Usage:
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);
Complete Reference Article
I've ported this solution to Swift 2.2. Note that I've changed the alpha
parameter to use a default set to 1.0. I've also updated the int type to UInt32
as required by the NSScanner
class in Swift 2.2.
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: NSScanner = NSScanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
// Scan hex value
scanner.scanHexInt(&hexInt)
return hexInt
}
Using the same logic with changes applied for swift 4,
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexStr: hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: Scanner = Scanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
// Scan hex value
scanner.scanHexInt32(&hexInt)
return hexInt
}
Color Hex References
HTML Color Names and Codes
Color Hex Color Codes
A concise solution:
// Assumes input like "#00FF00" (#RRGGBB).
+ (UIColor *)colorFromHexString:(NSString *)hexString {
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}
You can make a extension like this
extension UIColor{
convenience init(rgb: UInt, alphaVal: CGFloat) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: alphaVal
)
}
}
And use it anywhere like this
UIColor(rgb: 0xffffff, alphaVal: 0.2)