1, hex value color conversion
#import<UIKit/UIKit.h>@interfaceUicolor (Extension)//converts to the corresponding RGB color based on unsigned 32-bit integers+(Instancetype) Sy_colorwithhex: (u_int32_t) hex;@end#import "Uicolor+extension.h"@implementationUicolor (Extension)+(Instancetype) Sy_colorwithhex: (u_int32_t) hex{intRed = (Hex &0xFF0000) >> -; intGreen = (Hex &0x00FF00) >>8; intBlue = hex &0x0000FF; return[Uicolor colorwithred:red/255.0green:green/255.0blue:blue/255.0Alpha1.0];}@end
2. Convert Uicolor to RGB value
-(Nsmutablearray *) Changeuicolortorgb: (Uicolor *) Color {nsmutablearray*rgbstrvaluearr =[[Nsmutablearray alloc] init]; NSString*rgbstr =Nil; //get the RGB value descriptionNSString *rgbvalue = [NSString stringWithFormat:@"%@", color]; //separating RGB value descriptions into stringsNsarray *rgbarr = [Rgbvalue componentsseparatedbystring:@" "]; //Get Red value intR = [[Rgbarr objectatindex:1] Intvalue] *255; Rgbstr= [NSString stringWithFormat:@"%d", R]; [Rgbstrvaluearr ADDOBJECT:RGBSTR]; //Get Green value intg = [[Rgbarr objectatindex:2] Intvalue] *255; Rgbstr= [NSString stringWithFormat:@"%d", G]; [Rgbstrvaluearr ADDOBJECT:RGBSTR]; //get the Blue value intb = [[Rgbarr objectatindex:3] Intvalue] *255; Rgbstr= [NSString stringWithFormat:@"%d", b]; [Rgbstrvaluearr ADDOBJECT:RGBSTR]; //returns an array that holds the RGB values return[Rgbstrvaluearr autorelease]; }
3,16 binary color (HTML color value) string to Uicolor
+ (Uicolor *) Hexstringtocolor: (NSString *) Stringtoconvert {nsstring*cstring =[[Stringtoconvert stringbytrimmingcharactersinset:[nscharacterset Whitespaceandnewlinecharacterset]] Uppercasestring]; //String should be 6 or 8 characters if([cString Length] <6)return[Uicolor Blackcolor]; //strip 0X If it appears if([cString Hasprefix:@"0X"]) cString = [cString substringfromindex:2]; if([cString Hasprefix:@"#"]) cString = [cString substringfromindex:1]; if([cString length]! =6)return[Uicolor Blackcolor]; //separate into R, G, b substringsNsrange Range; Range.location=0; Range.length=2; NSString*rstring =[cString Substringwithrange:range]; Range.location=2; NSString*gstring =[cString Substringwithrange:range]; Range.location=4; NSString*bstring =[cString Substringwithrange:range]; //Scan ValuesUnsignedintR, 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:1.0f]; }
Uicolor various color conversions