Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created April 7, 2023 03:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianselig/5497c7798bc51a806931f35e982402b5 to your computer and use it in GitHub Desktop.
Save christianselig/5497c7798bc51a806931f35e982402b5 to your computer and use it in GitHub Desktop.
extension UIColor {
/// Blends this color into the specified color, as if this color was overlaid on top of the other at the specified alpha, but our result will instead be opaque. For instance if self was green, and we passed white and 0.1 alpha/opacity, the result would be a light, faded green.
///
/// - Note: This process is also called alpha compositing.
func blend(intoColor otherColor: UIColor, atOpacity alpha: CGFloat) -> UIColor {
let sourceRGB = rgb
let otherRGB = otherColor.rgb
return UIColor(
red: (sourceRGB.red * alpha) + (otherRGB.red * (1.0 - alpha)),
green: (sourceRGB.green * alpha) + (otherRGB.green * (1.0 - alpha)),
blue: (sourceRGB.blue * alpha) + (otherRGB.blue * (1.0 - alpha)),
alpha: 1.0
)
}
var rgb: (red: CGFloat, green: CGFloat, blue: CGFloat) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
getRed(&red, green: &green, blue: &blue, alpha: nil)
return (red, green, blue)
}
}
@christianselig
Copy link
Author

Can be used like:

view.backgroundColor = UIColor(hexcode: "2CB416").blend(intoColor: .white, atAlpha: 0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment