Objective-CでCSSでよく使うようなABCDEFFFのようなHex encodeされた形式の文字列からUIColorを生成する方法の紹介です。

   1  @interface UIColor (HexEncoding)
   2  + (UIColor*)colorFromString:(NSString*)string;
   3  - (NSString*)encodeToString;
   4  @end
   5  
   6  @implementation UIColor (HexEncoding)
   7  
   8  + (UIColor*)
   9  colorFromString:(NSString*)string
  10  {
  11    NSScanner *scanner = [NSScanner scannerWithString: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 colorWithRed:red green:green blue:blue alpha:alpha];
  19  }
  20  
  21  - (NSString*)encodeToString
  22  {
  23    const CGFloat *components = CGColorGetComponents(self.CGColor);
  24    return [NSString stringWithFormat:@"%02x%02x%02x%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にメソッドカテゴリを追加しています。 encodeToStringのほうでは、0.5を足してroundをかけていますが、 状況に応じてfloorにしたりceilにしたりしてください。

また、この例ではComponentsのサイズが4である事を期待しています。 そうではない色を扱うときには問題が発生しますので、ご注意ください。

posted by Png genki on Fri 7 Nov 2008 at 12:20

Comments:

or Preview
Social Bookmarks
  • Delicious
  • B_entry1009
  • Clip_16_12_w
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ