Created
February 13, 2018 05:46
-
-
Save aChase55/e505923bcf0f3f1a500a2c1eaf41716d to your computer and use it in GitHub Desktop.
Expressing RGB Colors as Arrays in Swift
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
//Cleanly instantiate UIColors using 1 or 3 Int, Double, Float, or CGFloat Values | |
//UIColor convience initializer UIColor(4, 20, 69) | |
//UIColor convience initializer for gray(all three values the same) UIColor(69) | |
//Instantiate gray from a number: 210.rgbTriple() | |
//Instantiate color from an array of numbers:[40, 33, 60].rgbColor() | |
//Optionally express an alpha value | |
//UIColor(4, 20, 69, 0.4) | |
//[69, 0.2].rgbColor() | |
import Foundation | |
protocol RGBNormalized { | |
var rgb:CGFloat { get } | |
var cgFloat:CGFloat { get } | |
} | |
extension RGBNormalized { | |
func rgbTriple() -> UIColor { return UIColor.init(self) } | |
} | |
extension Int:RGBNormalized { | |
var rgb:CGFloat { return CGFloat(self) / 255.0 } | |
var cgFloat:CGFloat { return CGFloat(self) } | |
} | |
extension Double:RGBNormalized { | |
var rgb:CGFloat { return CGFloat(self / 255.0) } | |
var cgFloat:CGFloat { return CGFloat(self) } | |
} | |
extension Float:RGBNormalized { | |
var rgb:CGFloat { return CGFloat(self / 255.0) } | |
var cgFloat:CGFloat { return CGFloat(self) } | |
} | |
extension CGFloat { | |
var rgb:CGFloat { return self / 255.0 } | |
var cgFloat:CGFloat { return CGFloat(self) } | |
} | |
extension Array where Element == RGBNormalized { | |
func rgbColor() -> UIColor { | |
switch count { | |
case 1: return UIColor(self[0]) | |
case 2: return UIColor(self[0], self[1]) | |
case 3: return UIColor(self[0], self[1], self[2]) | |
case 4: return UIColor(self[0], self[1], self[2], self[3]) | |
default: return UIColor.black | |
} | |
} | |
} | |
extension UIColor { | |
convenience init(_ r:RGBNormalized, _ g:RGBNormalized, _ b:RGBNormalized, _ a:RGBNormalized = 1.0) { | |
self.init(red: r.rgb, green: g.rgb, blue: b.rgb, alpha: a.cgFloat) | |
} | |
convenience init(_ v:RGBNormalized, _ a:RGBNormalized = 1.0) { | |
let value:CGFloat = v.rgb | |
self.init(red: value, green: value, blue: value, alpha: a.cgFloat) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment