Skip to content

Instantly share code, notes, and snippets.

@Sorix
Created January 27, 2017 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sorix/36436b33537192e60ca3948dbbd48131 to your computer and use it in GitHub Desktop.
Save Sorix/36436b33537192e60ca3948dbbd48131 to your computer and use it in GitHub Desktop.
UIColor with hex methods (init from hex, return hex value)
import UIKit
public extension UIColor {
/// Initializes and returns a color object using the specified hex value
///
/// - Parameter hex: hex value, example: `#ffffff` or `ffffff`
public convenience init(hex: String) {
let hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
scanner.scanHexInt32(&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)
}
/// Returns hex value of a color object.
var hex: 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment