Skip to content

Instantly share code, notes, and snippets.

@Kaji01
Forked from fxm90/UIColor+Initializers.swift
Created August 11, 2020 08:45
Show Gist options
  • Save Kaji01/185d80d9ef42386ce0a337d2a8be6b9e to your computer and use it in GitHub Desktop.
Save Kaji01/185d80d9ef42386ce0a337d2a8be6b9e to your computer and use it in GitHub Desktop.
Create UIColor from RGB, RGBA, Hex or Hex-String ("#ffffff")
public extension UIColor {
/// Create color from RGB(A)
///
/// Parameters:
/// - absoluteRed: Red value (between 0 - 255)
/// - green: Green value (between 0 - 255)
/// - blue: Blue value (between 0 - 255)
/// - alpha: Blue value (between 0 - 255)
///
/// Returns: UIColor instance.
convenience init(absoluteRed red: Int, green: Int, blue: Int, alpha: Int = 255) {
let normalizedRed = CGFloat(red) / 255.0
let normalizedGreen = CGFloat(green) / 255.0
let normalizedBlue = CGFloat(blue) / 255.0
let normalizedAlpha = CGFloat(alpha) / 255.0
self.init(
red: normalizedRed,
green: normalizedGreen,
blue: normalizedBlue,
alpha: normalizedAlpha
)
}
/// Create color from an hexadecimal integer value (e.g. 0xFFFFFF)
///
/// Note:
/// - Based on: http://stackoverflow.com/a/24263296
///
/// Parameters:
/// - hex: Hexadecimal integer for color
///
/// Returns: UIColor instance.
convenience init(hex: Int) {
self.init(
absoluteRed: (hex >> 16) & 0xff,
green: (hex >> 8) & 0xff,
blue: hex & 0xff
)
}
/// Create color from an hexadecimal string value (e.g. "#FFFFFF" / "FFFFFF")
///
/// Note:
/// - Based on: http://stackoverflow.com/a/27203691
///
/// Parameters:
/// - hex: Hexadecimal string for color
///
/// Returns: UIColor instance.
convenience init(hex: String) {
var normalizedHexColor = hex
.trimmingCharacters(in: .whitespacesAndNewlines)
.uppercased()
if normalizedHexColor.hasPrefix("#") {
normalizedHexColor = String(normalizedHexColor.dropFirst())
}
// Convert to hexadecimal color (string) to integer
var hex: UInt32 = 0
Scanner(string: normalizedHexColor).scanHexInt32(&hex)
self.init(
hex: Int(hex)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment