29
20

More than 3 years have passed since last update.

[Swift5] 画像の色を変更する

Last updated at Posted at 2019-10-17

やりたいこと

changeColor.png
この黒い電球を...
スクリーンショット 2019-10-17 14.56.35.png スクリーンショット 2019-10-17 14.55.59.png

こんな感じに色を変えたい!!

やり方

コードなし

1.Assets.xcassetsを開き、画像を選択する
スクリーンショット 2021-05-27 14.02.02.png

2.attribute inspectorのRender Asを[default -> Template Image] に変更する
スクリーンショット 2021-05-27 14.04.43.png

3.Storyboard上でimageViewのTint Colorを好きな色に変更する
スクリーンショット 2021-05-27 14.07.49.png

コードで実装

import UIKit

class ViewController: UIViewController {

    // imageのRenderingModeをalwaysTemplateに変更
    let image: UIImage = (UIImage(named: "light")!.withRenderingMode(.alwaysTemplate))
    let imageView: UIImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // 画像の大きさと位置を調整
        let screenWidth: CGFloat = view.frame.size.width
        let screenHeight: CGFloat = view.frame.size.height
        let imgWidth: CGFloat = image.size.width
        let imgHeight: CGFloat = image.size.height
        let scale: CGFloat = screenWidth / imgWidth
        let rect: CGRect = CGRect(x: 0, y: 0,
                                  width: imgWidth * scale,
                                  height: imgHeight * scale)
        imageView.frame = rect
        imageView.center = CGPoint(x: screenWidth / 2, y: screenHeight / 2)

        // imageViewにimageを代入
        self.imageView.image = self.image
        // imageViewのtintColorを好きな色に変更
        self.imageView.tintColor = .orange
        // imageViewを表示
        self.view.addSubview(self.imageView)
    }
}

備考

記載内容を2021年仕様に更新しました。

参考記事

29
20
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
29
20