Created
April 23, 2018 15:21
-
-
Save aydenp/f11c4adfcd3fc2dd1a37af420cbb8a62 to your computer and use it in GitHub Desktop.
Easily get RGB, HSL, white, and alpha information, whether a colour is light in Swift. Also can transition between two colours using the float you provide and tell you if a provided colour is lighter or darker.
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
// | |
// UIColor+RGBA.swift | |
// | |
// Created by Ayden Panhuyzen on 2018-04-10. | |
// Copyright © 2018 Ayden Panhuyzen. All rights reserved. | |
// https://gist.github.com/aydenp | |
// | |
import UIKit | |
extension UIColor { | |
var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { | |
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 | |
_ = getRed(&r, green: &g, blue: &b, alpha: &a) | |
return (r: r, g: g, b: b, a: a) | |
} | |
var hsba: (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat) { | |
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 | |
_ = getHue(&h, saturation: &s, brightness: &b, alpha: &a) | |
return (h: h, s: s, b: b, a: a) | |
} | |
var whiteAndAlpha: (white: CGFloat, alpha: CGFloat) { | |
var white: CGFloat = 0, alpha: CGFloat = 0 | |
_ = getWhite(&white, alpha: &alpha) | |
return (white: white, alpha: alpha) | |
} | |
func transitioned(to colour2: UIColor, with progress: CGFloat) -> UIColor { | |
func tween(value: CGFloat, with value2: CGFloat, progress: CGFloat) -> CGFloat { | |
return value + (value2 - value) * progress | |
} | |
let (r, g, b, a) = rgba, (r2, g2, b2, a2) = colour2.rgba | |
return UIColor(red: tween(value: r, with: r2, progress: progress), green: tween(value: g, with: g2, progress: progress), blue: tween(value: b, with: b2, progress: progress), alpha: tween(value: a, with: a2, progress: progress)) | |
} | |
var isLight: Bool { | |
let (_, _, b, _) = hsba | |
return b > 0.5 | |
} | |
/// Return the current colour with the alpha multiplied by alphaFactor. Unlike withAlphaComponent(_:), this doesn't just return the colour with the provided alpha, it multiplies the current alpha by your factor (0.5 * 0.5 = 0.25). | |
func with(alphaFactor: CGFloat) -> UIColor { | |
let (_, alpha) = whiteAndAlpha | |
return withAlphaComponent(alpha * alphaFactor) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment