Skip to content

Commit cac20a0

Browse files
committed
✨ custom hex color parsing with alpha support
1 parent ecd2523 commit cac20a0

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//
2+
// File.swift
3+
//
4+
//
5+
// Created by Igor Kulman on 07.02.2021.
6+
//
7+
// adapted from https://stackoverflow.com/a/33397427
8+
9+
import Foundation
10+
import Cocoa
11+
12+
extension NSColor {
13+
convenience init?(hexString: String) {
14+
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
15+
var int = UInt64()
16+
Scanner(string: hex).scanHexInt64(&int)
17+
let a, r, g, b: UInt64
18+
switch hex.count {
19+
case 3: // RGB (12-bit)
20+
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
21+
case 6: // RGB (24-bit)
22+
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
23+
case 8: // ARGB (32-bit)
24+
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
25+
default:
26+
return nil
27+
}
28+
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
29+
}
30+
}

0 commit comments

Comments
 (0)