Color Literal 给出的颜色与 UIColor init 不同(我无法比较它们)

Color Literal gives different colors than UIColor init (I can't compare them)

我在我的代码库中以两种方式创建颜色:使用颜色文字和使用 UIColor(red:green:blue:) 初始值设定项。这些颜色看起来一样,但当我尝试比较它们时,它们的成分略有不同。

为了有一个方便的接受整数而不是浮点数的初始化,我有一个扩展:

extension UIColor {

    convenience init(red: Int, green: Int, blue: Int) {
        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
    }
}

当我尝试测试颜色是否相同时,我的测试失败了:

func testColorComparision() {
    let literalColor = #colorLiteral(red: 1, green: 0.5764705882, blue: 0, alpha: 1) // This was a picked-up color "tangerine" rgb(255,147,0)
    let rgbColor = UIColor(red: 255, green: 147, blue: 0)
    XCTAssertEqual(literalColor, rgbColor) // Colors are not the same!
}

原来是我的扩展代码有误。 UIColor(red:green:blue:) 接受 CGFloats 但那些 CGFloats 应该是 64 位时代之前的数字。 CGFloat 在 32 位架构中以 float 表示,但在 64 位架构中表示为 double。但是,UIColors 的组件是 32 位数字。我修改了我的扩展名:

extension UIColor {

    convenience init(red: Int, green: Int, blue: Int) {
        self.init(red: CGFloat(Float(red)/255.0), green: CGFloat(Float(green)/255.0), blue: CGFloat(Float(blue)/255.0), alpha: 1.0)
    }
}

测试通过。第一个转换是将一个数字作为 Float,第二个转换是让 init 接受的 CGFloat 数字。