Objective-
1 @interface UIColor (HexEncoding) 2 + (UIColor*)colorFromS tring:(NSString*)string; 3 - (NSString*)encodeToSt ring; 4 @end 5 6 @implementa tion UIColor (HexEncodin g) 7 8 + (UIColor*) 9 colorFromS tring:(NSString*)string 10 { 11 NSScanner *scanner = [NSScanner scannerWit hString:string]; 12 NSUInteger value; 13 [scanner scanHexInt :&value]; 14 CGFloat red = ((value & 0xFF000000 ) >> 24) / 255.0f; 15 CGFloat green = ((value & 0x00FF0000 ) >> 16) / 255.0f; 16 CGFloat blue = ((value & 0x0000FF00 ) >> 8) / 255.0f; 17 CGFloat alpha = ((value & 0x000000FF ) >> 0) / 255.0f; 18 return [UIColor colorWithR ed:red green:green blue:blue alpha:alpha]; 19 } 20 21 - (NSString*)encodeToSt ring 22 { 23 const CGFloat *components = CGColorGet Components (self.CGColor); 24 return [NSString stringWith Format:@"%02x%02x%0 2x%02x", 25 (int)(components [0]*255 + 0.5f), 26 (int)(components [1]*255 + 0.5f), 27 (int)(components [2]*255 + 0.5f), 28 (int)(components [3]*255 + 0.5f)]; 29 } 30 31 @end
わかりやすいように、UIColorにメソッドカテゴリを追加しています。
encodeToSt
のほうでは、0.5を足してroundをかけていますが、
状況に応じてfloorにしたりceilにしたりしてください。
また、この例ではComponents