Created
          March 9, 2020 23:57 
        
      - 
      
 - 
        
Save sneakyness/8809482fa3a64402e272db9ffc4c00b9 to your computer and use it in GitHub Desktop.  
    Swift 5 UIColor+hexString - Accepts RGB/RRGGBB/RRGGBBAA
  
        
  
    
      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
    
  
  
    
  | import Foundation | |
| import UIKit | |
| extension UIColor { | |
| convenience init(hexString: String) { | |
| var hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) | |
| if (hexString.hasPrefix("#")) { | |
| hexString.removeFirst() | |
| } | |
| if hexString.count == 3 { | |
| var fullString = "" | |
| for char in hexString { | |
| fullString.append(char) | |
| fullString.append(char) | |
| } | |
| hexString = fullString | |
| } | |
| if hexString.count == 6 { | |
| hexString.append("FF") | |
| } | |
| assert(hexString.count == 8, "invalid hex string used to init UIColor") | |
| let scanner = Scanner(string: hexString) | |
| var color: UInt64 = 0 | |
| scanner.scanHexInt64(&color) | |
| let mask = 0x00000000FF | |
| let r = Int(color >> 24) & mask | |
| let g = Int(color >> 16) & mask | |
| let b = Int(color >> 8) & mask | |
| let a = Int(color) & mask | |
| let red = CGFloat(r) / 255.0 | |
| let green = CGFloat(g) / 255.0 | |
| let blue = CGFloat(b) / 255.0 | |
| let alpha = CGFloat(a) / 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) | |
| } | |
| func toHexStringWithAlpha() -> 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 rgba:Int = (Int)(r*255)<<24 | (Int)(g*255)<<16 | (Int)(b*255)<<8 | (Int)(a*255)<<0 | |
| return String(format:"#%06x", rgba) | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
after displayed, the color value is incorrect