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 5 years have passed since last update.

[swift5] ボタンにセットした画像の色をコントロールする.

Posted at

結論

以下のように, 「画像の読み込み時」にRenderingModeにalwaysTemplateを指定します.


let img = UIImage(named: "test.png")?.withRenderingMode(.alwaysTemplate)

self.imgButton.setImage(img, for: .normal)
self.imgButton.tintColor = UIColor.green   //ボタンにセットした画像の色を緑にする.

注意事項

以下のように画像を取得してから, 違う行でRenderingModeを変更しても, 画像の色を変更することはできません. エラーは出ませんが, 画像取得時にRenderingModeを変更しなければならないようです.

////////////////////////////////////上手く行かない例///////////////////////////////
let img = UIImage(named: "test.png")

//ここ.
img?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
self.imgButton.setImage(img, for: .normal)
self.imgButton.tintColor = UIColor.green   

補足

UIImage.RenderingMode : 画像生成時(レンダリング)のモードを特定する.
alwaysTemplate : 入力画像のカラー情報を無視して, 画像を描画するようにする.
[参考]https://developer.apple.com/documentation/uikit/uiimage/renderingmode

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?