Skip to content

Instantly share code, notes, and snippets.

@pvroosendaal
Last active March 31, 2020 11:28
Show Gist options
  • Save pvroosendaal/5aca45dff84590ab4d92d7b151b21839 to your computer and use it in GitHub Desktop.
Save pvroosendaal/5aca45dff84590ab4d92d7b151b21839 to your computer and use it in GitHub Desktop.
UIColor extension to work with hex strings (Swift 4)
//
// UIColor+Extensions.swift
// Roadmap
//
// Created by Paul van Roosendaal on 19/06/2018.
// Copyright © 2018 Roadmap. All rights reserved.
//
// Origin: https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7
import UIKit
extension UIColor {
convenience init(hexString: String) {
let hexString = hexString.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)
}
var hexString: 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)
}
}
@igorkulman
Copy link

Beware, this crashes on iPhone 5 and all the 32bit devices because Int means Int32 not Int64 on them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment