LoginSignup
36
34

More than 5 years have passed since last update.

UIColor から UIImage を作る

Posted at

UIColor から UIImage を作りたい場面があったので、調べてみたところ、以下のような感じで作成することができました。

UIImage *(^createImageFromUIColor)(UIColor *) = ^(UIColor *color)
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(contextRef, [color CGColor]);
    CGContextFillRect(contextRef, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
};

でこれを、

// UIColor から UIImage を作成する
UIImage *redImage = createImageFromUIColor([UIColor redColor]);
UIImage *blueImage = createImageFromUIColor([UIColor blueColor]);
UIImage *yellowImage = createImageFromUIColor([UIColor yellowColor]);

// UIButton には setBackgroundColor:forState メソッドがない
[button setBackgroundImage:redColor forState:UIControlStateNormal];
[button setBackgroundImage:blueImage forState:UIControlStateHighlighted];
[button setBackgroundImage:yellow forState:UIControlStateSelected];

こんな感じにすることで、画像を用意しなくても、UIButton の UIControllState に応じた色を指定することができます。

最終的に画像を用意してもらうことがほとんどだと思いますが、RoundRect のボタンではなく、Custom で自分の好きな色を簡単に指定した場合に使えるんじゃないでしょうか。

36
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
34