Skip to content

Instantly share code, notes, and snippets.

@mteera
Last active December 4, 2017 11:32
Show Gist options
  • Save mteera/2f840d134955262a28f0f847241cc514 to your computer and use it in GitHub Desktop.
Save mteera/2f840d134955262a28f0f847241cc514 to your computer and use it in GitHub Desktop.
An extension to create custom colours and use hex values.
import UIKit
// creating a color object
extension UIColor {
static let foodBulbGreen = UIColor(r: 47, g: 212, b: 128, a: 1)
static let foodBulbOrange = UIColor(r: 255, g: 130, b: 98, a: 1)
}
// usage: UIColor.foodBulbGreen
// convert an existing color into a hex
extension UIColor {
var toHexString: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return String(
format: "%02X%02X%02X",
Int(r * 0xff),
Int(g * 0xff),
Int(b * 0xff)
)
}
}
// convert an existing hex string into a UIColor object
extension UIColor {
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff, alpha: 1
)
}
}
// usage: UIColor(hex: "89CFF0")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment