LoginSignup
2
1

More than 3 years have passed since last update.

UIColorとIntの相互変換

Last updated at Posted at 2020-07-05

n番煎じですが、Intとの相互変換についての日本語の記事が見当たらなかったため投稿します

使い方

let color = UIColor(hex: 0xff0000) // red
color.hex // 0xff0000
extension UIColor {
    convenience init(hex: Int) {
        let red = (hex & 0xff0000) >> 16
        let green = (hex & 0x00ff00) >> 8
        let blue = hex & 0x0000ff

        self.init(
            red: CGFloat(red) / 255,
            green: CGFloat(green) / 255,
            blue: CGFloat(blue) / 255,
            alpha: 1
        )
    }

    var hex: Int {
        var red = CGFloat(0)
        var green = CGFloat(0)
        var blue = CGFloat(0)
        getRed(&red, green: &green, blue: &blue, alpha: nil)

        return Int(red * 255) << 16
            + Int(green * 255) << 8
            + Int(blue * 255)
    }
}

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