我试图在Swift中使用十六进制颜色值,而不是UIColor允许您使用的少数标准值,但我不知道如何做到这一点。
示例:我如何使用#ffffff作为颜色?
我试图在Swift中使用十六进制颜色值,而不是UIColor允许您使用的少数标准值,但我不知道如何做到这一点。
示例:我如何使用#ffffff作为颜色?
当前回答
extension UIColor {
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)
}
}
使用这个扩展像:
let selectedColor = UIColor(hex: 0xFFFFFF)
let selectedColor = UIColor(hex: 0xFFFFFF, alpha: 0.5)
其他回答
斯威夫特2.3: 用户界面颜色扩展。我认为这样更简单。
extension UIColor {
static func colorFromHex(hexString: String, alpha: CGFloat = 1) -> UIColor {
//checking if hex has 7 characters or not including '#'
if hexString.characters.count < 7 {
return UIColor.whiteColor()
}
//string by removing hash
let hexStringWithoutHash = hexString.substringFromIndex(hexString.startIndex.advancedBy(1))
//I am extracting three parts of hex color Red (first 2 characters), Green (middle 2 characters), Blue (last two characters)
let eachColor = [
hexStringWithoutHash.substringWithRange(hexStringWithoutHash.startIndex...hexStringWithoutHash.startIndex.advancedBy(1)),
hexStringWithoutHash.substringWithRange(hexStringWithoutHash.startIndex.advancedBy(2)...hexStringWithoutHash.startIndex.advancedBy(3)),
hexStringWithoutHash.substringWithRange(hexStringWithoutHash.startIndex.advancedBy(4)...hexStringWithoutHash.startIndex.advancedBy(5))]
let hexForEach = eachColor.map {CGFloat(Int($0, radix: 16) ?? 0)} //radix is base of numeric system you want to convert to, Hexadecimal has base 16
//return the color by making color
return UIColor(red: hexForEach[0] / 255, green: hexForEach[1] / 255, blue: hexForEach[2] / 255, alpha: alpha)
}
}
用法:
let color = UIColor.colorFromHex("#25ac09")
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)
在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 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)
斯威夫特5.0
你不能在Swift中直接使用#ffffff语法。以下是我用于网络相关项目的代码。支持alpha和三位数字。
用法示例(大写值也可以):
let hex = "#FADE2B" // yellow
let color = NSColor(fromHex: hex)
支持的字符串格式:
"fff" // RGB "#fff" // #RGB "ffff" // RGBA "#ffff" // #RGBA . "ffffff" // RRGGBB . "#ffffff" // #RRGGBB . "ffffffff" // RRGGBBAA . "#ffffffff" // #RRGGBBAA .
数字代表红色,绿色,蓝色和阿尔法(像透明度)。对于iOS,用UIColor替换NSColor。
代码:
extension NSColor {
/// Initialises NSColor from a hexadecimal string. Color is clear if string is invalid.
/// - Parameter fromHex: supported formats are "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA", with or without the # character
public convenience init(fromHex:String) {
var r = 0, g = 0, b = 0, a = 255
let offset = fromHex.hasPrefix("#") ? 1 : 0
let ch = fromHex.map{$0}
switch(ch.count - offset) {
case 8:
a = 16 * (ch[offset+6].hexDigitValue ?? 0) + (ch[offset+7].hexDigitValue ?? 0)
fallthrough
case 6:
r = 16 * (ch[offset+0].hexDigitValue ?? 0) + (ch[offset+1].hexDigitValue ?? 0)
g = 16 * (ch[offset+2].hexDigitValue ?? 0) + (ch[offset+3].hexDigitValue ?? 0)
b = 16 * (ch[offset+4].hexDigitValue ?? 0) + (ch[offset+5].hexDigitValue ?? 0)
break
case 4:
a = 16 * (ch[offset+3].hexDigitValue ?? 0) + (ch[offset+3].hexDigitValue ?? 0)
fallthrough
case 3: // Three digit #0D3 is the same as six digit #00DD33
r = 16 * (ch[offset+0].hexDigitValue ?? 0) + (ch[offset+0].hexDigitValue ?? 0)
g = 16 * (ch[offset+1].hexDigitValue ?? 0) + (ch[offset+1].hexDigitValue ?? 0)
b = 16 * (ch[offset+2].hexDigitValue ?? 0) + (ch[offset+2].hexDigitValue ?? 0)
break
default:
a = 0
break
}
self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
}
}
// Author: Andrew Kingdom
授权:CC BY
我发现这比下面的复制/粘贴更整洁
选择:
您可以删除#并将其存储为32位无符号整数字面量,由0x前缀表示,即0xffffff。不过,你仍然需要代码将其转换为颜色。
如果你想要一种非编程的方式来获取颜色:打开一个颜色选择器对话框,切换到colour Sliders > RGB Sliders,并将值粘贴/输入到“Hex color #”框中。(不要粘贴#散列符号。)