1
2

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 から rgba を取得

Posted at

各記事が乱立してるのと、CIColor 経由の記事があまり無いような気がしたので書きました。
他にも方法があれば教えてください。

CIColor 経由で取得

やり方はいくつもありますが、おそらく一番手っ取り早い方法。

let color: UIColor = .red
let ciColor = CIColor(color: color)
ciColor.red   // 1.0
ciColor.green // 0.0
ciColor.blue  // 0.0
ciColor.alpha // 1.0

CGColor 経由で取得

そんな大きな問題は無いのかもしれないけど、 optional型 という面倒くささと、配列なので fatal error: Index out of range の恐れがなんとなくある。

let color: UIColor = .red        
color.cgColor.components![0]
color.cgColor.components![1]
color.cgColor.components![2]
color.cgColor.components![3]

ポインタ 経由で取得

事前に変数を用意しなければいけないデメリット。

let color: UIColor = .red

var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0

color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
print(red, green, blue, alpha)

環境

  • Swift 4.2

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?