Skip to content

Instantly share code, notes, and snippets.

@ashtonmeuser
Last active November 9, 2017 20:56
Show Gist options
  • Select an option

  • Save ashtonmeuser/5e41e5f4cfa48e09e36e51358c6d16b2 to your computer and use it in GitHub Desktop.

Select an option

Save ashtonmeuser/5e41e5f4cfa48e09e36e51358c6d16b2 to your computer and use it in GitHub Desktop.
Generates dark UIColor from a numeric string provided a radix
//
// DarkColorFromHash.swift
//
// Created by Ashton Meuser on 2017-04-26.
// Copyright © 2017 Ashton Meuser. All rights reserved.
//
import Foundation
import UIKit
extension String {
func trimNumeric(for bits: Int, radix: Int = 10) -> String {
let max: Double = pow(2.0, Double(bits)) // Maximum representable
let cuttoff = Int(log(max) / log(Double(radix)))
return String(self.suffix(cuttoff))
}
}
static func darkColor(from numeric: String, radix: Int = 10) -> UIColor {
let trimmed = numeric.trimNumeric(for: 32, radix: radix) // Avoid overflow
guard let number = UInt32(trimmed, radix: radix) else {
return UIColor.clear // If radix can't be represented by string
}
let hue = CGFloat(number % 256) / 256.0 // Bits 0 to 7
let saturation = CGFloat(number >> 8 % 128 + 128) / 256.0 // Bits 8 to 11
let brightness = CGFloat(number >> 12 % 256) / 256.0 // Bits 12 to 19
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment