我在这里有点迷路了。我正在编写CGColor的扩展,它从十六进制值(字符串)和可选的alpha值(CGFloat)返回CGColor。返回新的CGColor实例时,发生以下错误:
'init(red:gee:blue:alpha)' is unavailable
给出以下信息:
这是完整的扩展代码:
import Foundation
import CoreGraphics
extension CGColor {
/// Construct a CGColor from a hex value and an optional alpha value.
///
/// - Parameter hex: The hex value to use for the rgb value, must be in the form of "#ffffff"
/// - Parameter alpha: Optional alpha value, ranges from 0 to 1.0
///
/// - Returns: A CGColor or nil if the provided hex value is invalid.
static func from(hex: String, alpha: CGFloat = 1.0) -> CGColor? {
// not a hex value: missing prefix or invalid character count
guard hex.hasPrefix("#") || hex.count == 7 else {
return nil
}
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
scanner.scanHexInt64(&hexNumber)
let r = CGFloat((hexNumber & 0xff000000) >> 16) / 255
let g = CGFloat((hexNumber & 0x00ff0000) >> 8) / 255
let b = CGFloat(hexNumber & 0x0000ff00) / 255
// here comes the error: 'init(red:green:blue:alpha)' is unavailable
return CGColor(
red: r,
green: g,
blue: b,
alpha: alpha
)
}
}
[编辑]
对于上下文:此代码是针对iOS和macOS的通用框架的一部分。该框架解析了一大堆描述几何和颜色对象的文本文件。颜色以十六进制值提供。
此CGColor扩展名用于从解析的十六进制值返回CGColor。
代码中的一些示例:
// the geometry object, which has a color
public struct Geometry {
public let color: Color
}
// the color definition for the geometry object
public struct Color {
public let id: ColorID
public let value: String
public let alpha: Int
// some code left out
public var cgColor: CGColor {
return CGColor?.from(hex: value, alpha: alphaValue)
}
}
如果使用框架的应用需要颜色:
let geometry = fromParsingFramework.geometry()
if let color = geometry.color.cgColor
答案 0 :(得分:1)
由于该初始化程序仅适用于macOS,因此您可以将其替换为以下内容:
let comps = [r,g,b,alpha]
return CGColor(colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, components: comps)
如果您的框架仅需要支持iOS 13 + / macOS 10.15+,则可以使用新的初始化程序:
return CGColor(srgbRed: r, green: g, blue: b, alpha: alpha)