如何在Swift中将Color Literal转换为cgColor?

How to convert Color Literal to cgColor in the Swift?

var CodeBackground = #colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1960784314, alpha: 1)

cells?.layer.borderColor = //... how can i set this color literal to cgColor?

据我所知如何在 Swift

中将 UIColor 转换为 cgColor

例如

UIColor.black.cgColor

Bingo,但是 Swift

中的 cgColor 的 Color Literal 呢?

谢谢。

  • 因为,您已经知道将 colorLiteral 用作 cgcolor 的更简单方法,我将跳到另一种方法...
  • 为此,您需要一个自定义函数,它从 colorLiteral 获取颜色值(红色、绿色、蓝色),如下所示

    extension UIColor {
        func rgb() -> (red:Int, green:Int, blue:Int, alpha:Int)? {
        var fRed : CGFloat = 0
        var fGreen : CGFloat = 0
        var fBlue : CGFloat = 0
        var fAlpha: CGFloat = 0
        if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
            let iRed = Int(fRed * 255.0)
            let iGreen = Int(fGreen * 255.0)
            let iBlue = Int(fBlue * 255.0)
            let iAlpha = Int(fAlpha)
    
            _ = (iAlpha << 24) + (iRed << 16) + (iGreen << 8) + iBlue
            return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
        } else {
            // Could not extract RGBA components:
            return nil
        }
    }
    }
    //It's more convenient to use function in `UIColor` extension
    
  • 现在,创建此函数后,您可以将 colorliteral 转换为 cgColor,如下所示...

    let CodeBackground = #colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1960784314, alpha: 1)
    let rgblit = CodeBackground.rgb()
    let Converted_cgColor = CGColor(srgbRed: CGFloat(integerLiteral: rgblit!.red), green: CGFloat(integerLiteral: rgblit!.green), blue: CGFloat(integerLiteral: rgblit!.blue), alpha: CGFloat(integerLiteral: rgblit!.alpha))
    
  • 可以直接用Converted_cgColor喜欢

    cells?.layer.borderColor = Converted_cgColor
    

希望对您有所帮助