104
84

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift] iOS で画像の色を動的に変える

Last updated at Posted at 2015-06-19

画像の色を動的に変えたい

ボタンなどの画像の色を、選択中/非選択中や有効/無効などで色を変えたいこと多いですよね。
状態に合わせた色を毎回用意するのって大変です、変更したいときとか特に。

UIImageRenderingMode.AlwaysTemplate を使う

UIImage で指定できる UIImageRenderingMode.AlwaysTemplate は画像のα値だけで描画してくれます。
色は TintColor に従うので、 TintColor を変更することで色を変えることができます。

# UIImageView の場合
let imageView = UIImageView(image: UIImage(named: "HeaderLogo")?.imageWithRenderingMode(.AlwaysTemplate))
imageView.tintColor = UIColor.greenColor()

# UIButton の場合
let button = UIButton(frame: CGRectMake(0, 0, 100, 30))
let backImage = UIImage(named: "BackButton")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
button.setImage(backImage, forState: UIControlState.Normal)
button.tintColor = UIColor.greenColor()

これを使えば画像を何種類も用意しなくて済むので便利です。

104
84
2

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
104
84

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?