Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extension to provide an equivalent opaque UIColor to a UIColor with alpha channel. So: f(r,g,b,a) == (r,g,b,1)
import UIKit
public extension UIColor {
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (red, green, blue, alpha)
}
func opaqueEquivalent(withBackground color: UIColor = .white) -> UIColor {
let bColor = color.components
let fColor = components
let alpha = fColor.alpha
func finalChannel(_ fColor: CGFloat, _ bColor: CGFloat) -> CGFloat {
(1 - alpha) * bColor + (fColor * alpha)
}
let newRed = finalChannel(fColor.red, bColor.red)
let newGreen = finalChannel(fColor.green, bColor.green)
let newBlue = finalChannel(fColor.blue, bColor.blue)
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.