How to Create a Hex Color String Uicolor Initializer in Swift

How to create a hex color string UIColor initializer in Swift?

Xcode 9 • Swift 4 or later

extension UIColor {
convenience init?(hexaRGB: String, alpha: CGFloat = 1) {
var chars = Array(hexaRGB.hasPrefix("#") ? hexaRGB.dropFirst() : hexaRGB[...])
switch chars.count {
case 3: chars = chars.flatMap { [$0, $0] }
case 6: break
default: return nil
}
self.init(red: .init(strtoul(String(chars[0...1]), nil, 16)) / 255,
green: .init(strtoul(String(chars[2...3]), nil, 16)) / 255,
blue: .init(strtoul(String(chars[4...5]), nil, 16)) / 255,
alpha: alpha)
}

convenience init?(hexaRGBA: String) {
var chars = Array(hexaRGBA.hasPrefix("#") ? hexaRGBA.dropFirst() : hexaRGBA[...])
switch chars.count {
case 3: chars = chars.flatMap { [$0, $0] }; fallthrough
case 6: chars.append(contentsOf: ["F","F"])
case 8: break
default: return nil
}
self.init(red: .init(strtoul(String(chars[0...1]), nil, 16)) / 255,
green: .init(strtoul(String(chars[2...3]), nil, 16)) / 255,
blue: .init(strtoul(String(chars[4...5]), nil, 16)) / 255,
alpha: .init(strtoul(String(chars[6...7]), nil, 16)) / 255)
}

convenience init?(hexaARGB: String) {
var chars = Array(hexaARGB.hasPrefix("#") ? hexaARGB.dropFirst() : hexaARGB[...])
switch chars.count {
case 3: chars = chars.flatMap { [$0, $0] }; fallthrough
case 6: chars.append(contentsOf: ["F","F"])
case 8: break
default: return nil
}
self.init(red: .init(strtoul(String(chars[2...3]), nil, 16)) / 255,
green: .init(strtoul(String(chars[4...5]), nil, 16)) / 255,
blue: .init(strtoul(String(chars[6...7]), nil, 16)) / 255,
alpha: .init(strtoul(String(chars[0...1]), nil, 16)) / 255)
}
}

if let textColor = UIColor(hexa: "00F") {
print(textColor) // r 0.0 g 0.0 b 1.0 a 1.0
}

if let textColor = UIColor(hexaRGB: "00F") {
print(textColor) // r 0.0 g 0.0 b 1.0 a 1.0
}


UIColor(hexaRGB: "#00F") // r 0.0 g 0.0 b 1.0 a 1.0
UIColor(hexaRGB: "#00F", alpha: 0.5) // r 0.0 g 0.0 b 1.0 a 0.5

UIColor(hexaRGB: "#0000FF") // r 0.0 g 0.0 b 1.0 a 1.0
UIColor(hexaRGB: "#0000FF", alpha: 0.5) // r 0.0 g 0.0 b 1.0 a 0.5

UIColor(hexaRGBA: "#0000FFFF") // r 0.0 g 0.0 b 1.0 a 1.0
UIColor(hexaRGBA: "#0000FF7F") // r 0.0 g 0.0 b 1.0 a 0.498

UIColor(hexaARGB: "#FF0000FF") // r 0.0 g 0.0 b 1.0 a 1.0
UIColor(hexaARGB: "#7F0000FF") // r 0.0 g 0.0 b 1.0 a 0.498

How to use hex color values

#ffffff are actually 3 color components in hexadecimal notation - red ff, green ff and blue ff. You can write hexadecimal notation in Swift using 0x prefix, e.g 0xFF

To simplify the conversion, let's create an initializer that takes integer (0 - 255) values:

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
)
}
}

Usage:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)

How to get alpha?

Depending on your use case, you can simply use the native UIColor.withAlphaComponent method, e.g.

let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)

Or you can add an additional (optional) parameter to the above methods:

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
)
}

(we cannot name the parameter alpha because of a name collision with the existing initializer).

Called as:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)

To get the alpha as an integer 0-255, we can

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
)
}

Called as

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)
let color2 = UIColor(argb: 0xFFFFFFFF)

Or a combination of the previous methods. There is absolutely no need to use strings.

Button Text - UIColor from Hex? SWIFT

This would be the code:

UIColor(red: 255/255, green: 204/255, blue: 0/255, alpha: 1.0) /* #ffcc00 */

also a very useful tool/ website for converting the colors into useful Swift code:

https://www.ralfebert.de/snippets/ios/swift-uicolor-picker/

Edit:

Example:

self.button.setTitleColor(UIColor(red:0.96, green:0.28, blue:0.28, alpha:1.0), forState: .Normal)

or if you want a cleaner solution:

var myColor = UIColor(red:0.96, green:0.28, blue:0.28, alpha:1.0)
self.button.setTitleColor(myColor, forState: .Normal)

Use Hex color in SwiftUI

You're almost there, you were using the wrong initialiser parameter:

extension Color {
init(hex: String) {
let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int: UInt64 = 0
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) = (1, 1, 1, 0)
}

self.init(
.sRGB,
red: Double(r) / 255,
green: Double(g) / 255,
blue: Double(b) / 255,
opacity: Double(a) / 255
)
}
}

How do I convert a UIColor to a 3/4/6/8 digits hexadecimal string in Swift?

Here's an extension for UIColor that can provide hexStrings in many formats including 3, 4, 6, and 8 digit forms:

extension UIColor {
enum HexFormat {
case RGB
case ARGB
case RGBA
case RRGGBB
case AARRGGBB
case RRGGBBAA
}

enum HexDigits {
case d3, d4, d6, d8
}

func hexString(_ format: HexFormat = .RRGGBBAA) -> String {
let maxi = [.RGB, .ARGB, .RGBA].contains(format) ? 16 : 256

func toI(_ f: CGFloat) -> Int {
return min(maxi - 1, Int(CGFloat(maxi) * f))
}

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)

let ri = toI(r)
let gi = toI(g)
let bi = toI(b)
let ai = toI(a)

switch format {
case .RGB: return String(format: "#%X%X%X", ri, gi, bi)
case .ARGB: return String(format: "#%X%X%X%X", ai, ri, gi, bi)
case .RGBA: return String(format: "#%X%X%X%X", ri, gi, bi, ai)
case .RRGGBB: return String(format: "#%02X%02X%02X", ri, gi, bi)
case .AARRGGBB: return String(format: "#%02X%02X%02X%02X", ai, ri, gi, bi)
case .RRGGBBAA: return String(format: "#%02X%02X%02X%02X", ri, gi, bi, ai)
}
}

func hexString(_ digits: HexDigits) -> String {
switch digits {
case .d3: return hexString(.RGB)
case .d4: return hexString(.RGBA)
case .d6: return hexString(.RRGGBB)
case .d8: return hexString(.RRGGBBAA)
}
}
}

Examples

print(UIColor.red.hexString(.d3))  // #F00
print(UIColor.red.hexString(.d4)) // #F00F
print(UIColor.red.hexString(.d6)) // #FF0000
print(UIColor.red.hexString(.d8)) // #FF0000FF

print(UIColor.green.hexString(.RGB)) // #0F0
print(UIColor.green.hexString(.ARGB)) // #F0F0
print(UIColor.green.hexString(.RGBA)) // #0F0F
print(UIColor.green.hexString(.RRGGBB)) // #00FF00
print(UIColor.green.hexString(.AARRGGBB)) // #FF00FF00
print(UIColor.green.hexString(.RRGGBBAA)) // #00FF00FF

print(UIColor(red: 0.25, green: 0.5, blue: 0.75, alpha: 0.3333).hexString()) // #4080c055

How to use hex color values

#ffffff are actually 3 color components in hexadecimal notation - red ff, green ff and blue ff. You can write hexadecimal notation in Swift using 0x prefix, e.g 0xFF

To simplify the conversion, let's create an initializer that takes integer (0 - 255) values:

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
)
}
}

Usage:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)

How to get alpha?

Depending on your use case, you can simply use the native UIColor.withAlphaComponent method, e.g.

let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)

Or you can add an additional (optional) parameter to the above methods:

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
)
}

(we cannot name the parameter alpha because of a name collision with the existing initializer).

Called as:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)

To get the alpha as an integer 0-255, we can

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
)
}

Called as

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)
let color2 = UIColor(argb: 0xFFFFFFFF)

Or a combination of the previous methods. There is absolutely no need to use strings.



Related Topics



Leave a reply



Submit