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.

UIColorで使っているRGBの値を取得する

Last updated at Posted at 2019-04-11

概要

UIColor(例えば、UIColor.red)で使われているRGB、alphaの値を取得したい

前提

  • Xcode 10.1
  • Swift 4.2

tl;dr

  • CGColor から取ってくる。
(lldb) po UIColor.yellow.cgColor.alpha
1.0
(lldb) po UIColor.yellow.cgColor.components
▿ Optional<Array<CGFloat>>
  ▿ some : 4 elements
    - 0 : 1.0
    - 1 : 1.0
    - 2 : 0.0
    - 3 : 1.0
print(UIColor.red.cgColor.components![0]) // Red 1.0

extend!

  • UIColorのextensionとして定義して便利に使う

import UIKit

extension UIColor {
    var redColor: CGFloat? {
        return self.cgColor.components?[0]
    }
    
    var greenColor: CGFloat? {
        return self.cgColor.components?[1]
    }
    
    var blueColor: CGFloat? {
        return self.cgColor.components?[2]
    }
    
    var alpha: CGFloat {
        return self.cgColor.alpha
    }
}

print(UIColor.red.redColor) // Optional(1.0)
print(UIColor.red.blueColor) // Optional(0.0)
print(UIColor.red.greenColor) // Optional(0.0)
print(UIColor.red.alpha) // 1.0
0
1
3

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?