Skip to content

Instantly share code, notes, and snippets.

@lukewakeford
Last active January 5, 2016 10:26
Show Gist options
  • Save lukewakeford/61a4ec79091ae83e7171 to your computer and use it in GitHub Desktop.
Save lukewakeford/61a4ec79091ae83e7171 to your computer and use it in GitHub Desktop.
Swift UIColor Extensions
extension UIColor {
class func fromHexString(hex:String) -> UIColor {
let hex = hex.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hex).scanHexInt(&int)
let a, r, g, b: UInt32
switch hex.characters.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)
}
return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
class func makeGradient(one:UIColor,two:UIColor,frame:CGRect) -> CAGradientLayer {
let gradient = CAGradientLayer()
let colour_array = [one.CGColor,two.CGColor]
gradient.frame = frame
gradient.colors = colour_array
return gradient
}
func lighterColor(percent : Double) -> UIColor {
return colorWithBrightnessFactor(CGFloat(1 + percent));
}
func darkerColor(percent : Double) -> UIColor {
return colorWithBrightnessFactor(CGFloat(1 - percent));
}
func colorWithBrightnessFactor(factor: CGFloat) -> UIColor {
var hue : CGFloat = 0
var saturation : CGFloat = 0
var brightness : CGFloat = 0
var alpha : CGFloat = 0
if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha)
} else {
return self;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment