如何使用hex颜色值
我试图在Swift中使用hex颜色值,而不是UIColor
允许使用的less数标准颜色值,但我不知道如何去做。
例如:我将如何使用#ffffff
作为颜色?
#ffffff
实际上是以hex表示的三种颜色分量 – 红色的ff
,绿色的ff
和蓝色的ff
。 您可以使用0x
前缀在Swift中编写hex符号,例如0xFF
为了简化转换,让我们创build一个带有整数(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)
为了得到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)
或者以前的方法的组合。 绝对不需要使用string。
这是一个函数,它接受一个hexstring并返回一个UIColor。
(您可以input任何格式的hexstring: ffffff
或ffffff
)
Swift 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) ) }
Swift 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) ) }
用法:
var color1 = hexStringToUIColor("#d3d3d3")
资料来源: arshad / gist:de147c42d7b3063ef7bc
编辑:更新了代码。 谢谢,Hlung和jaytrixz!
Swift 3 UIColor扩展:
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) } }
用法 :
let darkGrey = UIColor(hexString: "#757575")
Swift 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)
使用Swift 2.0和Xcode 7.0.1,你可以创build这个函数:
// 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)) }
Swift 3:通过UIColor支持hex和CSS颜色名称
要点代码
示例string:
-
Orange
,Lime
,Tomato
等 -
Clear
,Transparent
,nil
和空string良率[UIColor clearColor]
-
abc
-
abc7
-
#abc7
-
00FFFF
-
#00FFFF
-
00FFFF77
游乐场输出:
这个答案显示了如何在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 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) } }
你可以像这样用hex来直接创buildUIColor
let carrot = UIColor.uicolorFromHex(0xe67e22, alpha: 1))
斯威夫特3版Ethan Strider回答:
func hexStringToUIColor (_ hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines as CharacterSet).uppercased() if (cString.hasPrefix("#")) { cString = cString.substring(from: cString.characters.index(cString.startIndex, offsetBy: 1)) } 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) ) }
最新的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颜色
let color1 = UIColor(hexString: "#FF323232")
这是UIColor
上的一个带有hexstring的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) } }
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 2.0
下面的代码是在xcode 7.2上testing的
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 } }
Swift 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) ) }
我在Swift 2.2中创build了另外一个UIColor extension
,它可以使用hex值UIColor
直,愿意帮助某人:
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) } }
像这样使用它:
UIColor(hex: 0xffffff) // r 1.0 g 1.0 b 1.0 a 1.0 UIColor(hex: 0xffffff, alpha: 0.5) // r 1.0 g 1.0 b 1.0 a 0.5
你可以在UIColor上使用这个扩展,它将string(hex,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)) } }
只是第一个答案的一些addiotion
(有没有cehcked的alpha,可能需要添加一个if netHext > 0xffffff
):
extension UIColor { struct COLORS_HEX { static let Primary = 0xffffff static let PrimaryDark = 0x000000 static let Accent = 0xe89549 static let AccentDark = 0xe27b2a static let TextWhiteSemiTransparent = 0x80ffffff } convenience init(red: Int, green: Int, blue: Int, alphaH: 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") assert(alphaH >= 0 && alphaH <= 255, "Invalid alpha component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alphaH) / 255.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff, alphaH: (netHex >> 24) & 0xff) } }
支持7种hex颜色types
有七种hex颜色格式:“#FF0000”,“0xFF0000”,“FF0000”,“F00”,“红色”,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
警告:这不是一个“单一文件解决scheme”,有一些依赖关系,但是search它们可能比从头开始研究更快。
固定链接:
https://github.com/eonist/Element/wiki/Progress#supporting-7-hex-color-types
Swift 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()
Swift 2.3:UIColor扩展。 我认为它更简单。
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")
快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) } }
苹果电脑公司哈弗build造这样的,但我们正在定制为您的轻松。 对于所有来自其他编程语言的人来说,这种方法会很容易。
用法:
十进制RGB瓦尔:
UIColor(255,155,55) UIColor(255,155,55, 200)
hexRGB Val:
UIColor("FDB") UIColor("FFDDBB") UIColor("AAFFDDBB") |OR| UIColor("#FDB") UIColor("#FFDDBB") UIColor("#AAFFDDBB")
在课程外的任何文件中粘贴以下代码
extension UIColor { convenience init(_ RedPsgVar: Int, _ GrnPsgVar: Int, _ BluPsgVar: Int, _ OpcPsgVar: Int? = 255) { let RedVal = CGFloat(RedPsgVar)/255 let GrnVal = CGFloat(GrnPsgVar)/255 let BluVal = CGFloat(BluPsgVar)/255 let OpcVal = CGFloat(OpcPsgVar!)/255 self.init(red: RedVal, green: GrnVal, blue: BluVal, alpha: OpcVal) } convenience init(_ HexPsgVar: String) { var HexVar:String = HexPsgVar.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString if (HexVar.hasPrefix("#")) { HexVar = HexVar.substringFromIndex(HexVar.startIndex.advancedBy(1)) } var RgbVar:UInt32 = 0 NSScanner(string: HexVar).scanHexInt(&RgbVar) let OpcVal, RedVal, GrnVal, BluVal: UInt32 switch HexVar.characters.count { case 3: // RGB (12-bit) (OpcVal, RedVal, GrnVal, BluVal) = (255, (RgbVar >> 8) * 17, (RgbVar >> 4 & 0xF) * 17, (RgbVar & 0xF) * 17) case 6: // RGB (24-bit) (OpcVal, RedVal, GrnVal, BluVal) = (255, RgbVar >> 16, RgbVar >> 8 & 0xFF, RgbVar & 0xFF) case 8: // ARGB (32-bit) (OpcVal, RedVal, GrnVal, BluVal) = (RgbVar >> 24, RgbVar >> 16 & 0xFF, RgbVar >> 8 & 0xFF, RgbVar & 0xFF) default: (OpcVal, RedVal, GrnVal, BluVal) = (100, 100, 100, 100) } self.init(red: CGFloat(RedVal) / 255, green: CGFloat(GrnVal) / 255, blue: CGFloat(BluVal) / 255, alpha: CGFloat(OpcVal) / 255) } }
Swift 4版本看起来像这样:
extension UIColor { convenience init(hexString: String, alpha: CGFloat = 1.0) { let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let scanner = Scanner(string: hexString) if (hexString.hasPrefix("#")) { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&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:alpha) } 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 String(format:"#%06x", rgb) }
}
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)
Swift 3
extension UIColor { convenience init(r: Int, g: Int, b: Int, a: Int = 255) { self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0) } convenience init(netHex:Int) { self.init(r:(netHex >> 16) & 0xff, g:(netHex >> 8) & 0xff, b:netHex & 0xff) } }
使用:
self.view.backgroundColor = UIColor(netHex: 0x27ae60)
我做了一个小function,把它放在我可以在全球范围内使用的地方,并使用swift 2.1:
func getColorFromHex(rgbValue:UInt32)->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:1.0) }
用法:
getColorFromHex(0xffffff)
extension UIColor { convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) { self.init(red: r/255, green: g/255, blue: b/255, alpha: a) } convenience init(hex: Int, alpha: CGFloat = 1) { self.init(r: CGFloat((hex >> 16) & 0xff), g: CGFloat((hex >> 08) & 0xff), b: CGFloat((hex >> 00) & 0xff), a: alpha) } }
以编程方式添加颜色最简单的方法是使用ColorLiteral 。
如示例中所示,只需添加ColorLiteral属性,Xcode会提示您提供一个可供select的颜色列表。 这样做的好处是较less的代码, 添加hex值或RGB 。 您还将从故事板中获取最近使用的颜色。
例如: self.view.backgroundColor = ColorLiteral