CGColorGetComponents() not returning the correct values for black and for white

拟墨画扇 提交于 2019-12-17 16:55:13

问题


Has anyone experienced this problem? It looks like a bug in Apple's code and I will submit a radar if people agree that this code should do what I think it should do. I'm not all that familiar with CoreGraphics color management, hence I'm asking before I bug Apple with a bug report.

This is straight out of a template project and the only non-template code is what you see below. Note that the red, green, and blue colors all show the correct component values but not white or black.

The problem persists if you change the order with, say, black and white first, then red, green, blue.

This is Swift 1.2 and Xcode 6.3.1 (6D1002).

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        let colorComps = [
            CGColorGetComponents(UIColor.redColor().CGColor),
            CGColorGetComponents(UIColor.greenColor().CGColor),
            CGColorGetComponents(UIColor.blueColor().CGColor),
            CGColorGetComponents(UIColor.blackColor().CGColor),
            CGColorGetComponents(UIColor.whiteColor().CGColor)
        ]

        var components = [CGFloat]()
        for cc in colorComps
        {
            for i in 0...3 { components.append(cc[i]) }
        }

        println("components: \(components)")
    }
}

回答1:


What you're not grasping is that nothing about CGColorGetComponents makes any claims or guarantees about how many components there are or what they mean. That information is contained in the color's color space. If you look at the color space of white and black, you will see they are both forms of grey:

let sp = CGColorGetColorSpace(UIColor.whiteColor().CGColor)
println(sp) // kCGColorSpaceDeviceGrey

Thus, they are expressed in just two values: the amount of grey, and the alpha.

Hence, white is [1.0,1.0] - which, if you ignore the extra two numbers which you should not have been reading in the first place, is exactly what you got.

Similarly, black is [0.0,1.0], which is also what you got.



来源:https://stackoverflow.com/questions/30020420/cgcolorgetcomponents-not-returning-the-correct-values-for-black-and-for-white

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!