Last active
August 29, 2015 14:20
-
-
Save karlwilcox/5d9f53cc70a1445e1a67 to your computer and use it in GitHub Desktop.
Adds a convenience init to UIColor to allow it to be created from a hex string as in HTML or CSS colour specifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIColorByHexString.swift | |
// | |
// Created by Karl Wilcox on 10/05/2015. | |
// Copyright (c) 2015 Karl Wilcox. All rights reserved. | |
// | |
import Foundation | |
import UIKit | |
/** | |
* Adds a convenience init to UIColor to allow it to be created from a 3, 6 or 8 digit hexadecimal string, | |
* with an optional '#' or '0x' prefix, as per HTML and CSS colour specifications | |
* A 3 digit hex string has each digit doubled (ie. #123 becomes #112233) and becomes a 6 digit string | |
* A 6 digit hex string is converted to red, green and blue components and is opaque (alpha = 1) | |
* An 8 digit hex string is converted to red, green, blue and alpha components | |
* There are no errors reported, the init always succeeds, if no conversion is possible opaque black is produced | |
* | |
* Example usage: let aliceBlue = UIColor(hexString: "#f0f8ff") | |
* | |
*/ | |
extension UIColor { | |
convenience init(hexString:String) { | |
var redFloat:Float = 0.0 | |
var greenFloat:Float = 0.0 | |
var blueFloat:Float = 0.0 | |
var alphaFloat:Float = 255.0 | |
var digits = Array(hexString) | |
var numDigits = digits.count | |
if numDigits >= 3 { | |
if digits[0] == "#" { | |
digits.removeAtIndex(0) | |
numDigits -= 1 | |
} else if digits[0] == "0" && digits[1] == "x" { | |
digits.removeAtIndex(0) | |
digits.removeAtIndex(0) | |
numDigits -= 2 | |
} | |
} | |
if numDigits == 3 { // double up hex digits | |
digits = [digits[0], digits[0], digits[1], digits[1], digits[2], digits[2]] | |
numDigits = 6 | |
} | |
// Only go ahead if length is 6 or 8 (extra digits are ignored) | |
if numDigits >= 6 { | |
NSScanner(string: "0x\(digits[0])\(digits[1])").scanHexFloat(&redFloat) | |
NSScanner(string: "0x\(digits[2])\(digits[3])").scanHexFloat(&greenFloat) | |
NSScanner(string: "0x\(digits[4])\(digits[5])").scanHexFloat(&blueFloat) | |
if numDigits >= 8 { | |
NSScanner(string: "0x\(digits[6])\(digits[7])").scanHexFloat(&alphaFloat) | |
} | |
} | |
self.init(red: CGFloat(redFloat / 255), green: CGFloat(greenFloat / 255), blue: CGFloat(blueFloat / 255), alpha: CGFloat(alphaFloat / 255)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment