Estou tentando usar valores de cores hexadecimais no Swift, em vez dos poucos padrões que UIColor
permitem você use, mas não tenho idéia de como fazê-lo.
Exemplo: como eu usaria #ffffff
como cor?
Estou tentando usar valores de cores hexadecimais no Swift, em vez dos poucos padrões que UIColor
permitem você use, mas não tenho idéia de como fazê-lo.
Exemplo: como eu usaria #ffffff
como cor?
Respostas:
#ffffff
são na verdade três componentes de cor em notação hexadecimal - vermelho ff
, verde ff
e azul ff
. Você pode escrever notação hexadecimal no Swift usando o 0x
prefixo, por exemplo0xFF
Para simplificar a conversão, vamos criar um inicializador que aceite valores inteiros (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
)
}
}
Uso:
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)
Como obter alfa?
Dependendo do seu caso de uso, você pode simplesmente usar o UIColor.withAlphaComponent
método nativo , por exemplo
let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)
Ou você pode adicionar um parâmetro adicional (opcional) aos métodos acima:
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
)
}
(não podemos nomear o parâmetro alpha
devido a uma colisão de nomes com o inicializador existente).
Chamado como:
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)
Para obter o alfa como um número inteiro de 0 a 255, podemos
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
)
}
Chamado como
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)
let color2 = UIColor(argb: 0xFFFFFFFF)
Ou uma combinação dos métodos anteriores. Não há absolutamente nenhuma necessidade de usar strings.
alpha
Esta é uma função que pega uma sequência hexadecimal e retorna um UIColor.
(Você pode inserir cadeias hexadecimais com o formato: #ffffff
ou ffffff
)
Uso:
var color1 = hexStringToUIColor("#d3d3d3")
Swift 5: (Swift 4 ou mais)
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)
)
}
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)
)
}
Fonte: arshad / gist: de147c42d7b3063ef7bc
Editar: atualizado o código. Obrigado, Hlung, Jaytrixz, Ahmad F., Kegham K e Adam Waite!
countelements
agora é apenas count
:)
count
agora, em vez de countElements
, alguma ideia do que eles querem que usemos?
cString = cString.substringFromIndex(advance(cString.startIndex, 1))
para cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
a Swift 2.2 Xcode 7.3
UInt32
paraUInt64
scanHexInt32
. Use a UInt64
e em scanHexInt64
vez disso.
Swift 5 (Swift 4, Swift 3) Extensão 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)
}
}
Uso :
let darkGrey = UIColor(hexString: "#757575")
Versão 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
}
}
Uso
let purple = UIColor(hex: 0xAB47BC)
let foo: Int = 0x123ABC
- observe o '0x'
Swift 4 : Combinando as respostas de Sulthan e 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
)
}
}
Exemplos de uso:
let myColor = UIColor(hexFromString: "4F9BF5")
let myColor = UIColor(hexFromString: "#4F9BF5")
let myColor = UIColor(hexFromString: "#4F9BF5", alpha: 0.5)
Com o Swift 2.0 e o Xcode 7.0.1, você pode criar esta função:
// 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))
}
e depois use-o desta maneira:
let color1 = colorWithHexString("#1F437C")
Atualizado para o 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))
}
Sequências de exemplo:
Orange
, Lime
,Tomato
, Etc.Clear
, Transparent
, nil
, E um rendimento de cadeia vazia[UIColor clearColor]
abc
abc7
#abc7
00FFFF
#00FFFF
00FFFF77
Saída do parque infantil:
A maneira mais simples de adicionar cores por meio de programação é usando o ColorLiteral .
Basta adicionar a propriedade ColorLiteral como mostrado no exemplo, o Xcode solicitará uma lista completa de cores que você pode escolher. A vantagem de fazer isso é um código menor, adicione valores HEX ou RGB . Você também obterá as cores usadas recentemente no storyboard.
O aviso "'scanHexInt32' foi preterido no iOS 13.0" foi corrigido.
A amostra deve funcionar no Swift2.2 e acima (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)
}
}
Use-os como abaixo:
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)
Esta resposta mostra como fazê-lo no Obj-C. A ponte é para usar
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)
Mesclamos algumas idéias deste tópico de respostas e atualizei-o para iOS 13 e Swift 5 .
extension UIColor {
convenience init(hex: String, alpha: CGFloat = 1.0) {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) { cString.removeFirst() }
if ((cString.count) != 6) {
self.init(hex: "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)
}
}
Você pode usá-lo assim:
UIColor(hex: "#ff0000") // with #
UIColor(hex: "ff0000") // without #
UIColor(hex: "ff0000", alpha: 0.5) // using optional alpha value
Outro método
Swift 3.0
Escreva uma extensão para 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)
}
}
você pode criar diretamente o UIColor com hexadecimal como este
let carrot = UIColor.uicolorFromHex(0xe67e22, alpha: 1))
Versão mais recente do 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)
}
}
Use na sua classe ou onde quer que você tenha convertido em hexcolor para uicolor, desta maneira
let color1 = UIColor(hexString: "#FF323232")
Aqui está o que estou usando. Funciona com seqüências de cores de 6 e 8 caracteres, com ou sem o símbolo #. O padrão é preto na versão e falha na depuração quando inicializado com uma sequência inválida.
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)
}
}
Uso:
UIColor(hex: "#75CC83FF")
UIColor(hex: "75CC83FF")
UIColor(hex: "#75CC83")
UIColor(hex: "75CC83")
Aqui está uma extensão Swift UIColor
que leva uma string hexadecimal:
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
}
}
Como usar
var color: UIColor = hexStringToUIColor(hex: "#00ff00"); // Without transparency
var colorWithTransparency: UIColor = hexStringToUIColor(hex: "#dd00ff00"); // With transparency
Baseado na resposta do Eduardo
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
apenas testar expressões regulares. string.range(of: pattern, options: .regularExpression)
funciona também
Você pode usá-lo rapidamente 5
SWIFT 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)
)
}
}
Exemplo:
let myColor = Color(hex:0xF2C94C)
Código:
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))
}
}
Swift 2.0:
Em 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{
/// 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)
}
}
Ligue usando UIColor (hexString: "sua sequência hexadecimal")
Existem 7 formatos de cores hexadecimais: "" # FF0000 "," 0xFF0000 "," FF0000 "," F00 "," vermelho ", 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
CUIDADO: Esta não é uma "solução de arquivo único", existem algumas dependências, mas procurá-las pode ser mais rápido do que pesquisar isso do zero.
Permalink:
https://github.com/eonist/Element/wiki/Progress#supporting-7-hex-color-types
Swift 2.0
O código abaixo é testado no 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
}
}
Swift 2.0:
Faça uma extensão do 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
}
}
Uso:
//Hex to Color
let countPartColor = UIColor(hexString: "E43038")
//Color to Hex
let colorHexString = UIColor(red: 228, green: 48, blue: 56, alpha: 1.0).toHexString()
Para rápido 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)
}
}
Você pode usar esta extensão no UIColor, que converte Sua String (Hexadecimal, RGBA) em UIColor e vice-versa.
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))
}
}
Extensão UIColor, isso irá ajudá-lo muito! (versão: Swift 4.0 )
import UIKit
extension UIColor {
/// rgb颜色
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r/255.0 ,green: g/255.0 ,blue: b/255.0 ,alpha:1.0)
}
/// 纯色(用于灰色)
convenience init(gray: CGFloat) {
self.init(red: gray/255.0 ,green: gray/255.0 ,blue: gray/255.0 ,alpha:1.0)
}
/// 随机色
class func randomCGColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
/// hex颜色-Int
convenience init(hex:Int, alpha:CGFloat = 1.0) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((hex & 0x0000FF) >> 0) / 255.0,
alpha: alpha
)
}
/// hex颜色-String
convenience init(hexString: String){
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
let scanner = Scanner(string: hexString)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hexString.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
alpha = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
red = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x000000FF) / 255.0
default:
log.info("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
log.error("Scan hex error")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}}
Gosto da resposta de @ Luca, pois acho que é a mais elegante.
No entanto , não quero minhas cores especificadas no ARGB . Eu prefiro o RGBA + também necessário hackear no caso de lidar com strings que especificam 1 caractere para cada um dos canais " #FFFA ".
Esta versão também adiciona um erro ao lançar + retira o caractere '#' se ele estiver incluído na string. Aqui está o meu formulário modificado para Swift.
public enum ColourParsingError: Error
{
case invalidInput(String)
}
extension UIColor {
public convenience init(hexString: String) throws
{
let hexString = hexString.replacingOccurrences(of: "#", with: "")
let hex = hexString.trimmingCharacters(in:NSCharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count
{
case 3: // RGB (12-bit)
(r, g, b,a) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17,255)
//iCSS specification in the form of #F0FA
case 4: // RGB (24-bit)
(r, g, b,a) = ((int >> 12) * 17, (int >> 8 & 0xF) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF,255)
case 8: // ARGB (32-bit)
(r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
throw ColourParsingError.invalidInput("String is not a valid hex colour string: \(hexString)")
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
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
}
}
Uso:
let white = UIColor(hex: "#ffffff")
#ffffff
são na verdade três componentes de cor em notação hexadecimal - vermelhoff
, verdeff
e azulff
. Você pode escrever notação hexadecimal no Swift usando o0x
prefixo, por exemplo0xFF
.