5
1

More than 3 years have passed since last update.

【Swift】ColorをRGBで指定する

Last updated at Posted at 2020-09-09

はじめに

SwiftでcolorをRGBで指定する方法を説明します。

Swiftでのcolor指定

まず通常の指定方法は

ViewController.swift
sampleView.backgroundColor = .blue

sampleView.backgroundColor = UIColor(red: 0.1, green: 0.5, blue: 1.0, alpha: 1.0)

sampleView.backgroundColor = UIColor(red: 30/255, green: 144/255, blue: 255/255, alpha: 1.0)

下に載せている記事が参考になるかと思いますが、SwiftでRGB指定しようとすると全ての値を255で割って分数表記にしないといけないため、若干めんどくさいです。
@shu26 さんのQiita
https://qiita.com/shu26/items/bc0a8a06019b24d799d4

そこで、RGBの値をそのまま利用するためのextensionを作成します。

255で割るためのextensionを作成する

UIColorとかの名前をつけたSwiftファイルに、extensionを作成します。

UIColor.swift
import UIKit

extension UIColor {
    static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor{
        return self.init(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1)
    }
}

Viewの色を変更してみる

作成したextensionを使ってViewの色を変更してみます。

ViewController.swift
sampleView.backgroundColor = UIColor.rgb(red: 121, green: 162, blue: 255)

rgbsample.png
これでRGBでcolorを指定することができるようになります!

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