Swift - UIColor extension

2018-06-19  本文已影响9人  Swift_Aramis

HexString - 传入类似 "#FF2A1A" 或 "FF2A1A" 格式字符串

/// Formats a hex color string to UIColor. If empty, Black. If invalid, White.
///
/// - Parameters: #00FFFF
/// - hexString: web-format hex color string "#FF2A1A" or "FF2A1A"
/// - alpha: default 1.0

convenience init(hexString: String, alpha: CGFloat = 1.0) {
var resultHexString = hexString
if resultHexString.hasPrefix("#") {
resultHexString.remove(at: resultHexString.startIndex)
}

let scanner = Scanner(string: resultHexString)
scanner.charactersToBeSkipped = CharacterSet.alphanumerics.inverted
var value: UInt32 = 0;
scanner.scanHexInt32(&value)
self.init(hex: value, alpha: alpha)
}

Hex - 传入类似 0xe44664 的16进制格式数值

/// Formats a hex color to UIColor.
///
/// - Parameters:
/// - hex: 16-formats 0xe44664
/// - alpha: default 1.0

convenience init(hex: UInt32, alpha: CGFloat = 1.0) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: alpha
)
}

rgb - 传入 rgb 数值

/// Formats rgb color to UIColor.
///
/// - Parameters:
/// - r:
/// - g:
/// - b:
/// - alpha: default 1.0

convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) {
self.init(
red: r / 255.0,
green: g / 255.0,
blue: b / 255.0,
alpha: alpha
)
}

git链接:https://github.com/Swift-Aramis/ColorHex

上一篇下一篇

猜你喜欢

热点阅读