我正在尝试在 Swift 中使用十六进制颜色值,而不是 UIColor
允许您使用的少数标准颜色值,但我不知道该怎么做。
示例:如何使用 #ffffff
作为颜色?
#ffffff
实际上是十六进制表示法的 3 个颜色分量 - 红色 ff
、绿色 ff
和蓝色 ff
。您可以使用 0x
前缀在 Swift 中编写十六进制表示法,例如 0xFF
。
#ffffff
实际上是十六进制表示法的 3 个颜色分量 - 红色 ff
、绿色 ff
和蓝色 ff
。您可以使用 0x
前缀在 Swift 中编写十六进制表示法,例如 0xFF
为了简化转换,让我们创建一个采用整数 (0 - 255) 值的初始化程序:
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
用法:
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)
如何获得阿尔法?
根据您的用例,您可以简单地使用本机 UIColor.withAlphaComponent
方法,例如
let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)
或者您可以在上述方法中添加一个附加(可选)参数:
convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: a
)
}
convenience init(rgb: Int, a: CGFloat = 1.0) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF,
a: a
)
}
(由于与现有初始化程序的名称冲突,我们无法命名参数 alpha
)。
称为:
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)
要将 alpha 设为 0-255 的整数,我们可以
convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: CGFloat(a) / 255.0
)
}
// let's suppose alpha is the first component (ARGB)
convenience init(argb: Int) {
self.init(
red: (argb >> 16) & 0xFF,
green: (argb >> 8) & 0xFF,
blue: argb & 0xFF,
a: (argb >> 24) & 0xFF
)
}
称为
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)
let color2 = UIColor(argb: 0xFFFFFFFF)
或者前面几种方法的组合。绝对不需要使用字符串。
这是一个接受十六进制字符串并返回 UIColor 的函数。
(您可以输入格式为 #ffffff
或 ffffff
的十六进制字符串)
用法:
var color1 = hexStringToUIColor("#d3d3d3")
斯威夫特 5:(斯威夫特 4+)
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
斯威夫特 3:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
斯威夫特 2:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
}
if ((cString.characters.count) != 6) {
return UIColor.grayColor()
}
var rgbValue:UInt32 = 0
NSScanner(string: cString).scanHexInt(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
来源:arshad/gist:de147c42d7b3063ef7bc
编辑:更新了代码。谢谢,Hlung、jaytrixz、Ahmad F、Kegham K 和 Adam Waite!
countelements
现在只是 count
:)
count
而不是 countElements
,知道他们想让我们使用什么吗?
cString = cString.substringFromIndex(advance(cString.startIndex, 1))
更改为 cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
UInt32
更改为 UInt64
scanHexInt32
。请改用 UInt64
和 scanHexInt64
。
Swift 5 (Swift 4, Swift 3) UIColor 扩展:
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt64()
Scanner(string: hex).scanHexInt64(&int)
let a, r, g, b: UInt64
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
用法:
let darkGrey = UIColor(hexString: "#757575")
斯威夫特 2.x 版本:
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hex).scanHexInt(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
UIColor
:
extension UIColor {
convenience init(hex: Int) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
}
}
CGColor
:
extension CGColor {
class func colorWithHex(hex: Int) -> CGColorRef {
return UIColor(hex: hex).CGColor
}
}
用法
let purple = UIColor(hex: 0xAB47BC)
let foo: Int = 0x123ABC
- 注意“0x”
Swift 4:结合 Sulthan 和 Luca Torella 的答案:
extension UIColor {
convenience init(hexFromString:String, alpha:CGFloat = 1.0) {
var cString:String = hexFromString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
var rgbValue:UInt32 = 10066329 //color #999999 if string has wrong format
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) == 6) {
Scanner(string: cString).scanHexInt32(&rgbValue)
}
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha
)
}
}
使用示例:
let myColor = UIColor(hexFromString: "4F9BF5")
let myColor = UIColor(hexFromString: "#4F9BF5")
let myColor = UIColor(hexFromString: "#4F9BF5", alpha: 0.5)
我已经从这个答案线程中合并了一些想法,并针对 iOS 13 和 Swift 5 进行了更新。
extension UIColor {
convenience init(_ hex: String, alpha: CGFloat = 1.0) {
var cString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if cString.hasPrefix("#") { cString.removeFirst() }
if cString.count != 6 {
self.init("ff0000") // return red color for wrong hex input
return
}
var rgbValue: UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha)
}
}
然后你可以像这样使用它:
UIColor("#ff0000") // with #
UIColor("ff0000") // without #
UIColor("ff0000", alpha: 0.5) // using optional alpha value
Swift 5.3 & SwiftUI:通过 UIColor 支持十六进制和 CSS 颜色名称
示例字符串:
橙子、青柠、番茄等
Clear、Transparent、nil 和空字符串产生 [UIColor clearColor]
美国广播公司
abc7
#abc7
00FFFF
#00FFFF
00FFFF77
https://i.stack.imgur.com/OgwHo.png
以编程方式添加颜色的最简单方法是使用 ColorLiteral。
只需像示例中所示添加属性 ColorLiteral,Xcode 将提示您提供可以选择的整个颜色列表。这样做的好处是代码更少,添加 HEX 值或 RGB。您还将从情节提要中获得最近使用的颜色。
https://i.stack.imgur.com/ylkWa.png
使用 Swift 2.0 和 Xcode 7.0.1 你可以创建这个函数:
// Creates a UIColor from a Hex string.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
return UIColor.grayColor()
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
然后以这种方式使用它:
let color1 = colorWithHexString("#1F437C")
为 Swift 4 更新
func colorWithHexString (hex:String) -> UIColor {
var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
if (cString.characters.count != 6) {
return UIColor.gray
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
警告“iOS 13.0 中不推荐使用‘scanHexInt32’”已修复。
该示例应适用于 Swift2.2 及更高版本(Swift2.x、Swift3.x、Swift4.x、Swift5.x):
extension UIColor {
// hex sample: 0xf43737
convenience init(_ hex: Int, alpha: Double = 1.0) {
self.init(red: CGFloat((hex >> 16) & 0xFF) / 255.0, green: CGFloat((hex >> 8) & 0xFF) / 255.0, blue: CGFloat((hex) & 0xFF) / 255.0, alpha: CGFloat(255 * alpha) / 255)
}
convenience init(_ hexString: String, alpha: Double = 1.0) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt64()
Scanner(string: hex).scanHexInt64(&int)
let r, g, b: UInt64
switch hex.count {
case 3: // RGB (12-bit)
(r, g, b) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(r, g, b) = (int >> 16, int >> 8 & 0xFF, int & 0xFF)
default:
(r, g, b) = (1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(255 * alpha) / 255)
}
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
self.init(red: (r / 255), green: (g / 255), blue: (b / 255), alpha: a)
}
}
像下面这样使用它们:
UIColor(0xF54A45)
UIColor(0xF54A45, alpha: 0.7)
UIColor("#f44")
UIColor("#f44", alpha: 0.7)
UIColor("#F54A45")
UIColor("#F54A45", alpha: 0.7)
UIColor("F54A45")
UIColor("F54A45", alpha: 0.7)
UIColor(r: 245.0, g: 73, b: 69)
UIColor(r: 245.0, g: 73, b: 69, a: 0.7)
https://i.stack.imgur.com/cr1Po.png
This 答案显示了如何在 Obj-C 中执行此操作。桥梁是使用
let rgbValue = 0xFFEEDD
let r = Float((rgbValue & 0xFF0000) >> 16)/255.0
let g = Float((rgbValue & 0xFF00) >> 8)/255.0
let b = Float((rgbValue & 0xFF))/255.0
self.backgroundColor = UIColor(red:r, green: g, blue: b, alpha: 1.0)
Swift 5:您可以在 Xcode 中创建颜色,如下图所示:
https://i.stack.imgur.com/RTY6f.png
您应该命名颜色,因为您通过名称引用颜色。如图2所示:
https://i.stack.imgur.com/MSns5.jpg
这是我正在使用的。适用于 6 和 8 个字符的颜色字符串,带或不带 # 符号。使用无效字符串初始化时,发布时默认为黑色,调试时崩溃。
extension UIColor {
public convenience init(hex: String) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 1
let hexColor = hex.replacingOccurrences(of: "#", with: "")
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
var valid = false
if scanner.scanHexInt64(&hexNumber) {
if hexColor.count == 8 {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
valid = true
}
else if hexColor.count == 6 {
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255
g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255
b = CGFloat(hexNumber & 0x0000ff) / 255
valid = true
}
}
#if DEBUG
assert(valid, "UIColor initialized with invalid hex string")
#endif
self.init(red: r, green: g, blue: b, alpha: a)
}
}
用法:
UIColor(hex: "#75CC83FF")
UIColor(hex: "75CC83FF")
UIColor(hex: "#75CC83")
UIColor(hex: "75CC83")
另一种方法
斯威夫特 3.0
为 UIColor 写一个扩展
// To change the HexaDecimal value to Corresponding Color
extension UIColor
{
class func uicolorFromHex(_ rgbValue:UInt32, alpha : CGFloat)->UIColor
{
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
let green = CGFloat((rgbValue & 0xFF00) >> 8) / 255.0
let blue = CGFloat(rgbValue & 0xFF) / 255.0
return UIColor(red:red, green:green, blue:blue, alpha: alpha)
}
}
你可以像这样直接用十六进制创建 UIColor
let carrot = UIColor.uicolorFromHex(0xe67e22, alpha: 1))
这是 UIColor
上的 Swift 扩展,它采用十六进制字符串:
import UIKit
extension UIColor {
convenience init(hexString: String) {
// Trim leading '#' if needed
var cleanedHexString = hexString
if hexString.hasPrefix("#") {
// cleanedHexString = dropFirst(hexString) // Swift 1.2
cleanedHexString = String(hexString.characters.dropFirst()) // Swift 2
}
// String -> UInt32
var rgbValue: UInt32 = 0
NSScanner(string: cleanedHexString).scanHexInt(&rgbValue)
// UInt32 -> R,G,B
let red = CGFloat((rgbValue >> 16) & 0xff) / 255.0
let green = CGFloat((rgbValue >> 08) & 0xff) / 255.0
let blue = CGFloat((rgbValue >> 00) & 0xff) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1.0)
}
}
最新的 swift3 版本
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
在你的课堂上使用,或者在你以这种方式将 hexcolor 转换为 uicolor 的地方使用
let color1 = UIColor(hexString: "#FF323232")
public static func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) == 6) {
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}else if ((cString.characters.count) == 8) {
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0x00FF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x0000FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x000000FF) / 255.0,
alpha: CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0
)
}else{
return UIColor.gray
}
}
如何使用
var color: UIColor = hexStringToUIColor(hex: "#00ff00"); // Without transparency
var colorWithTransparency: UIColor = hexStringToUIColor(hex: "#dd00ff00"); // With transparency
Swift 5/SwiftUI 的简单颜色扩展
例子:
let myColor = Color(hex:0xF2C94C)
代码:
import Foundation
import SwiftUI
extension UIColor {
convenience init(hex: Int) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
}
}
extension Color {
public init(hex: Int) {
self.init(UIColor(hex: hex))
}
}
带验证的十六进制
基于爱德华多的回答
细节
Xcode 10.0、斯威夫特 4.2
Xcode 10.2.1 (10E1001)、斯威夫特 5
解决方案
import UIKit
extension UIColor {
convenience init(r: UInt8, g: UInt8, b: UInt8, alpha: CGFloat = 1.0) {
let divider: CGFloat = 255.0
self.init(red: CGFloat(r)/divider, green: CGFloat(g)/divider, blue: CGFloat(b)/divider, alpha: alpha)
}
private convenience init(rgbWithoutValidation value: Int32, alpha: CGFloat = 1.0) {
self.init(
r: UInt8((value & 0xFF0000) >> 16),
g: UInt8((value & 0x00FF00) >> 8),
b: UInt8(value & 0x0000FF),
alpha: alpha
)
}
convenience init?(rgb: Int32, alpha: CGFloat = 1.0) {
if rgb > 0xFFFFFF || rgb < 0 { return nil }
self.init(rgbWithoutValidation: rgb, alpha: alpha)
}
convenience init?(hex: String, alpha: CGFloat = 1.0) {
var charSet = CharacterSet.whitespacesAndNewlines
charSet.insert("#")
let _hex = hex.trimmingCharacters(in: charSet)
guard _hex.range(of: "^[0-9A-Fa-f]{6}$", options: .regularExpression) != nil else { return nil }
var rgb: UInt32 = 0
Scanner(string: _hex).scanHexInt32(&rgb)
self.init(rgbWithoutValidation: Int32(rgb), alpha: alpha)
}
}
用法
let alpha: CGFloat = 1.0
// Hex
print(UIColor(rgb: 0x4F9BF5) ?? "nil")
print(UIColor(rgb: 0x4F9BF5, alpha: alpha) ?? "nil")
print(UIColor(rgb: 5217269) ?? "nil")
print(UIColor(rgb: -5217269) ?? "nil") // = nil
print(UIColor(rgb: 0xFFFFFF1) ?? "nil") // = nil
// String
print(UIColor(hex: "4F9BF5") ?? "nil")
print(UIColor(hex: "4F9BF5", alpha: alpha) ?? "nil")
print(UIColor(hex: "#4F9BF5") ?? "nil")
print(UIColor(hex: "#4F9BF5", alpha: alpha) ?? "nil")
print(UIColor(hex: "#4F9BF56") ?? "nil") // = nil
print(UIColor(hex: "#blabla") ?? "nil") // = nil
// RGB
print(UIColor(r: 79, g: 155, b: 245))
print(UIColor(r: 79, g: 155, b: 245, alpha: alpha))
//print(UIColor(r: 792, g: 155, b: 245, alpha: alpha)) // Compiler will throw an error, r,g,b = [0...255]
NSPredicate
只是为了测试正则表达式。 string.range(of: pattern, options: .regularExpression)
也可以。
您可以在 swift 5 中使用它
斯威夫特 5
import UIKit
extension UIColor {
static func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
斯威夫特 2.0:
在 viewDidLoad()
var viewColor:UIColor
viewColor = UIColor()
let colorInt:UInt
colorInt = 0x000000
viewColor = UIColorFromRGB(colorInt)
self.View.backgroundColor=viewColor
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
extension UIColor {
public convenience init?(hex: String) {
let r, g, b, a: CGFloat
if hex.hasPrefix("#") {
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
}
用法:
let white = UIColor(hex: "#ffffff")
斯威夫特 5
extension UIColor{
/// Converting hex string to UIColor
///
/// - Parameter hexString: input hex string
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt64()
Scanner(string: hex).scanHexInt64(&int)
let a, r, g, b: UInt64
switch hex.count {
case 3:
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6:
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8:
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
使用 UIColor(hexString: "your hex string") 调用
iOS 14、SwiftUI 2.0、Swift 5.1、Xcode beta12
extension Color {
static func hexColour(hexValue:UInt32)->Color
{
let red = Double((hexValue & 0xFF0000) >> 16) / 255.0
let green = Double((hexValue & 0xFF00) >> 8) / 255.0
let blue = Double(hexValue & 0xFF) / 255.0
return Color(red:red, green:green, blue:blue)
}
}
你用十六进制数调用它
let red = Color.hexColour(hexValue: 0xFF0000)
Xcode 13.2.1、M1、Swift 5.5
我们可以在 ColorLiterals 中使用 Hex
在 Xcode 中输入 #colorLiteral(
,这将触发并修复与 ColorLiterals 相关的错误
然后点击其他
https://i.stack.imgur.com/09p0V.png
然后选择 RGB 滑块,您现在可以看到 Hex 面板
https://i.stack.imgur.com/H1aoI.png
支持 7 种十六进制颜色类型
有 7 种十六进制颜色格式: ""#FF0000","0xFF0000", "FF0000", "F00", "red", 0x00FF00 , 16711935
NSColorParser.nsColor("#FF0000",1)//red nsColor
NSColorParser.nsColor("FF0",1)//red nsColor
NSColorParser.nsColor("0xFF0000",1)//red nsColor
NSColorParser.nsColor("#FF0000",1)//red nsColor
NSColorParser.nsColor("FF0000",1)//red nsColor
NSColorParser.nsColor(0xFF0000,1)//red nsColor
NSColorParser.nsColor(16711935,1)//red nsColor
注意:这不是“单一文件解决方案”,存在一些依赖关系,但寻找它们可能比从头开始研究更快。
固定链接:
https://github.com/eonist/Element/wiki/Progress#supporting-7-hex-color-types
斯威夫特 2.0
下面的代码在 xcode 7.2 上测试
import UIKit
extension UIColor{
public convenience init?(colorCodeInHex: String, alpha: Float = 1.0){
var filterColorCode:String = colorCodeInHex.stringByReplacingOccurrencesOfString("#", withString: "")
if filterColorCode.characters.count != 6 {
self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: CGFloat(alpha))
return
}
filterColorCode = filterColorCode.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
var range = Range(start: filterColorCode.startIndex.advancedBy(0), end: filterColorCode.startIndex.advancedBy(2))
let rString = filterColorCode.substringWithRange(range)
range = Range(start: filterColorCode.startIndex.advancedBy(2), end: filterColorCode.startIndex.advancedBy(4))
let gString = filterColorCode.substringWithRange(range)
range = Range(start: filterColorCode.startIndex.advancedBy(4), end: filterColorCode.startIndex.advancedBy(6))
let bString = filterColorCode.substringWithRange(range)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(alpha))
return
}
}
斯威夫特 2.0:
对 UIColor 进行扩展。
extension UIColor {
convenience init(hexString:String) {
let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let scanner = NSScanner(string: hexString as String)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:1)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return NSString(format:"#%06x", rgb) as String
}
}
用法:
//Hex to Color
let countPartColor = UIColor(hexString: "E43038")
//Color to Hex
let colorHexString = UIColor(red: 228, green: 48, blue: 56, alpha: 1.0).toHexString()
对于迅捷3
extension String {
var hexColor: UIColor {
let hex = trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
return .clear
}
return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
您可以在 UIColor 上使用此扩展,它将您的字符串(十六进制,RGBA)转换为 UIColor,反之亦然。
extension UIColor {
//Convert RGBA String to UIColor object
//"rgbaString" must be separated by space "0.5 0.6 0.7 1.0" 50% of Red 60% of Green 70% of Blue Alpha 100%
public convenience init?(rgbaString : String){
self.init(ciColor: CIColor(string: rgbaString))
}
//Convert UIColor to RGBA String
func toRGBAString()-> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return "\(r) \(g) \(b) \(a)"
}
//return UIColor from Hexadecimal Color string
public convenience init?(hexString: String) {
let r, g, b, a: CGFloat
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = hexString.substring(from: start)
if hexColor.characters.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
// Convert UIColor to Hexadecimal String
func toHexString() -> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return String(
format: "%02X%02X%02X",
Int(r * 0xff),
Int(g * 0xff),
Int(b * 0xff))
}
}
alpha