Created
December 6, 2019 03:16
-
-
Save cntrump/3be76233216aaede40656349de5772be to your computer and use it in GitHub Desktop.
add CSS Hex Color support for UIColor with Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extension UIColor { | |
| static func hex(_ val: UInt) -> UIColor { | |
| var r: UInt = 0, g: UInt = 0, b: UInt = 0; | |
| var a: UInt = 0xFF | |
| var rgb = val | |
| if (val & 0xFFFF0000) == 0 { | |
| a = 0xF | |
| if val & 0xF000 > 0 { | |
| a = val & 0xF | |
| rgb = val >> 4 | |
| } | |
| r = (rgb & 0xF00) >> 8 | |
| r = (r << 4) | r | |
| g = (rgb & 0xF0) >> 4 | |
| g = (g << 4) | g | |
| b = rgb & 0xF | |
| b = (b << 4) | b | |
| a = (a << 4) | a | |
| } else { | |
| if val & 0xFF000000 > 0 { | |
| a = val & 0xFF | |
| rgb = val >> 8 | |
| } | |
| r = (rgb & 0xFF0000) >> 16 | |
| g = (rgb & 0xFF00) >> 8 | |
| b = rgb & 0xFF | |
| } | |
| //NSLog("r:%X g:%X b:%X a:%X", r, g, b, a) | |
| return UIColor(red: CGFloat(r) / 255.0, | |
| green: CGFloat(g) / 255.0, | |
| blue: CGFloat(b) / 255.0, | |
| alpha: CGFloat(a) / 255.0) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example:
color:
#FFAABBalpha:#DDCSS Hex Color value is:
#FFAABBDDor#FABDor
so easy ~