. h
#import <UIKit/UIKit.h>
@interface Uicolor (WJ)
+ (Uicolor *) colorwithwjstring: (NSString *) color;
Gets the color from the hexadecimal string,
Color: support @ "#123456", @ "0x123456", @ "123456" three formats
+ (Uicolor *) colorwithwjstring: (NSString *) color alpha: (cgfloat) Alpha;
@end
. m
#import "Uicolor+wj.h"
@implementation Uicolor (WJ)
+ (Uicolor *) colorwithwjstring: (NSString *) color{
return [self colorwithwjstring:color alpha:1.0f];
}
Gets the color from the hexadecimal string,
Color: support @ "#123456", @ "0x123456", @ "123456" three formats
+ (Uicolor *) colorwithwjstring: (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, and the string starts at the position indexed to 2, up to 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];
}
Uicolor Classification 16 binary Turn RGB