Objective-CでCSSでよく使うようなABCDEFFFのようなHex encodeされた形式の文字列からUIColorを生成する方法の紹介です。
objective-c>>
@interface UIColor (HexEncoding)
- (UIColor*)colorFromString:(NSString*)string;
- (NSString*)encodeToString;
@end
@implementation UIColor (HexEncoding)
- (UIColor*)
colorFromString:(NSString*)string
{
NSScanner *scanner = [NSScanner scannerWithString:string];
NSUInteger value;
[scanner scanHexInt:&value];
CGFloat red = ((value & 0xFF000000) >> 24) / 255.0f;
CGFloat green = ((value & 0x00FF0000) >> 16) / 255.0f;
CGFloat blue = ((value & 0x0000FF00) >> 8) / 255.0f;
CGFloat alpha = ((value & 0x000000FF) >> 0) / 255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
- (NSString*)encodeToString
{
const CGFloat *components = CGColorGetComponents(self.CGColor);
return [NSString stringWithFormat:@"%02x%02x%02x%02x",
(int)(components[0]*255 + 0.5f),
(int)(components[1]*255 + 0.5f),
(int)(components[2]*255 + 0.5f),
(int)(components[3]*255 + 0.5f)];
}
@end
<<--
わかりやすいように、UIColorにメソッドカテゴリを追加しています。encodeToStringのほうでは、0.5を足してroundをかけていますが、
状況に応じてfloorにしたりceilにしたりしてください。
また、この例ではComponentsのサイズが4である事を期待しています。
そうではない色を扱うときには問題が発生しますので、ご注意ください。
posted by
genki on Fri 7 Nov 2008 at 12:10 with 0 comments