3
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.

NSColorから色情報を取得する

Last updated at Posted at 2016-12-14

少しつまづいたのでメモ

NSColorのRGB要素を取得したい時に、NSColorに対してColorSpaceを記述しなかったためクラッシュしました。

こうやろうとした

var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var blackColor = NSColor.black

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

落ちた

2016-12-14 15:45:12.840 com.apple.dt.Xcode.PlaygroundStub-macosx[4950:260043] *** -getRed:green:blue:alpha: not valid for the NSColor NSCalibratedWhiteColorSpace 0 1; need to first convert colorspace.

色空間を最初に設定せよと言われておる。

こうやったら動くよ

NSColorにColorSpaceを記述します。

var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var blackColor = NSColor.black

if let color = blackColor.usingColorSpaceName(NSCalibratedRGBColorSpace) {
    color.getRed(&red, green: &green, blue: &blue, alpha: nil)
}
print(red)
print(blue)
print(green)

これがしたかった

NSColorを16進文字列に直したかっただけです。

NSColor+Hex.swift
func hexStr() -> String {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        
        if let color = self.usingColorSpaceName(NSCalibratedRGBColorSpace) {
            color.getRed(&red, green: &green, blue: &blue, alpha: nil)
            let redHexString = String(Int(red * 255), radix: 16)
            let greenHexString = String(Int(green * 255), radix: 16)
            let blueHexString = String(Int(blue * 255), radix: 16)
            
            return redHexString + greenHexString + blueHexString
        }
        return ""
    }

参考

3
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
3
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?