#import <UIKit/UIKit.h>
@interface Uicolor (Hex)
default Alpha bit 1
+ (uicolor *) colorwithhexstring: (nsstring *) color;
gets the color from the hexadecimal string,
Color: Three formats supported @ "#123456", @ "0x123456", @ " 123456"
+ (uicolor *) colorwithhexstring: (nsstring *) color alpha: (cgfloat) Alpha;
@end
--------------------. m----------------
#import "Uicolor+hex.h"
@implementation Uicolor (Hex)
+ (uicolor *) colorwithhexstring: (nsstring *) color alpha: (cgfloat) Alpha
{
// Delete spaces in a string
nsstring *cstring = [[Color stringbytrimmingcharactersinset: [nscharacterset Whitespaceandnewlinecharacterset]] uppercasestring];
//String should be 6 or 8 characters
if ([cString length] < 6)
{
return [uicolor clearcolor];
}
//Strip 0X if it appears
// If it starts with 0x, then the string is truncated, starting at index 2 , until the end
if ([cString hasprefix:@ "0X"])
{
cString = [cString substringfromindex:2];
}
//If it starts with #, then the string is truncated, and the string starts at the position indexed to 1 , up to the end
if ([cString hasprefix:@ "#"])
{
cString = [cString substringfromindex:1];
}
if ([cString length]! = 6)
{
return [uicolor clearcolor];
}
//separate into R, G, b substrings
nsrange range;
Range. location = 0;
Range. length = 2;
//r
nsstring *rstring = [cString substringwithrange: Range];
//g
Range. location = 2;
nsstring *gstring = [cString substringwithrange: Range];
//b
Range. location = 4;
nsstring *bstring = [cString substringwithrange: Range];
//Scan values
unsigned int R, G, B;
[[nsscanner scannerwithstring: rString] scanhexint:&r];
[[nsscanner scannerwithstring: gstring] scanhexint:&g];
[[nsscanner Scannerwithstring:bstring] scanhexint:&b];
return [uicolor colorwithred:((float) R/ 255.0f) Green:(( float) G/ 255.0f) Blue:((float) b/ 255.0f) Alpha: Alpha];
}
The default alpha value is 1
+ (uicolor *) colorwithhexstring: (nsstring *) color
{
return [self colorwithhexstring: Color alpha:1.0f];
}
@end
Package of Uicolor