Skip to content

Instantly share code, notes, and snippets.

@vladimir-anisimov
Last active April 29, 2022 11:24
Show Gist options
  • Save vladimir-anisimov/098ee6d5833e2efc31a5c827d3018370 to your computer and use it in GitHub Desktop.
Save vladimir-anisimov/098ee6d5833e2efc31a5c827d3018370 to your computer and use it in GitHub Desktop.
import UIKit
extension UIColor {
convenience init(hexString: String, alpha: CGFloat = 1) {
self.init(hex: UInt(hexString.dropFirst(),
radix: 16) ?? 0, alpha: alpha)
}
convenience init(hex: UInt, alpha: CGFloat = 1) {
self.init(red: .init((hex & 0xff0000) >> 16) / 255,
green: .init((hex & 0xff00 ) >> 8) / 255,
blue: .init( hex & 0xff ) / 255,
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment