Created
January 14, 2016 08:43
-
-
Save FlexMonkey/7b66b0df7ab866dbc754 to your computer and use it in GitHub Desktop.
Handy UIColor extensions: multiply(), getRGBA() and getHex()
This file contains hidden or 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
import UIKit | |
typealias RGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) | |
extension UIColor | |
{ | |
func multiply(value: CGFloat) -> UIColor | |
{ | |
let newRed = getRGBA().red * value | |
let newGreen = getRGBA().green * value | |
let newBlue = getRGBA().blue * value | |
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0) | |
} | |
func getRGBA() -> RGBA | |
{ | |
func zeroIfDodgy(value: CGFloat) -> CGFloat | |
{ | |
return isnan(value) || isinf(value) ? 0 : value | |
} | |
if CGColorGetNumberOfComponents(self.CGColor) == 4 | |
{ | |
let colorRef = CGColorGetComponents(self.CGColor); | |
let redComponent = zeroIfDodgy(colorRef[0]) | |
let greenComponent = zeroIfDodgy(colorRef[1]) | |
let blueComponent = zeroIfDodgy(colorRef[2]) | |
let alphaComponent = zeroIfDodgy(colorRef[3]) | |
return RGBA(red: redComponent, | |
green: greenComponent, | |
blue: blueComponent, | |
alpha: alphaComponent) | |
} | |
else if CGColorGetNumberOfComponents(self.CGColor) == 2 | |
{ | |
let colorRef = CGColorGetComponents(self.CGColor); | |
let greyComponent = zeroIfDodgy(colorRef[0]) | |
let alphaComponent = zeroIfDodgy(colorRef[1]) | |
return RGBA(red: greyComponent, | |
green: greyComponent, | |
blue: greyComponent, | |
alpha: alphaComponent) | |
} | |
else | |
{ | |
return RGBA(red: 0, | |
green: 0, | |
blue: 0, | |
alpha: 0) | |
} | |
} | |
func getHex() -> String | |
{ | |
let rgba = self.getRGBA() | |
let red = String(format: "%02X", Int(rgba.red)) | |
let green = String(format: "%02X", Int(rgba.green)) | |
let blue = String(format: "%02X", Int(rgba.blue)) | |
return (red as String) + (green as String) + (blue as String) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment