0
1

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】画像の色を変更するには?

Posted at

はじめに

iOSアプリケーションを開発していく中で、画像の色を条件によって変更させたいシーンに遭遇しました。
自分は、各色の画像を用意するものだと思っていましたが調べてみたところコードで変更できることを知ったので今回まとめます。

開発環境

  • macOS Catalina version10.15.7
  • Xcode version12.2
  • Swift5

画像の反映方法

画像を反映させる際は、通常以下のように記載するかと思います。

imageView.image = UIImage(named: "画像ファイル名")

では画像の色を変更するにはどうすればいいのかと言うと、withRenderingMode()を用いてtintColorを指定することでできます。

imageView.image = UIImage(named: "画像ファイル名")?.withRenderingMode(.alwaysTemplete)
imageView.tintColor = .white //画像の色を白にする

ちなみにレンダリングモードの指定値は以下の通りです。解釈が間違っている可能性もあるため公式ドキュメントをご確認お願いします。

レンダリングモード 詳細
withRenderingMode(.automatic) コンテキストのレンダリング(?)
withRenderingMode(.alwaysOriginal) 常に元の画像を描画
withRenderingMode(.alwaysTemplete) 色情報を無視して、テンプレート画像を描画

参考
公式ドキュメント:UIImage Changing the Image Attributes

[公式ドキュメント:withRenderingMode(_:)]
(https://developer.apple.com/documentation/uikit/uiimage/1624153-withrenderingmode)

公式ドキュメント:UIImage .Rendering Mode

まとめ

今回は画像の色を変更する方法についてまとめました。

以上

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?