Get Slightly Lighter and Darker Color from UIColor

前端 未结 19 2383
猫巷女王i
猫巷女王i 2020-12-07 07:08

I was looking to be able to turn any UIColor into a gradient. The way I am intending to do this is by using Core Graphics to draw a gradient. What I am trying to do is to ge

19条回答
  •  有刺的猬
    2020-12-07 07:47

    I just wanted to give the same result, in RGB, than

    • placing the color with alpha x% over a white background to lighten
    • placing the color with alpha x% over a black background to darken

    Which gives the same result, AFAIK, than picking the color in a gradient 'color to white' or 'color to black', at x% of the gradient size.

    For that purpose, the math is simple:

    extension UIColor {
        func mix(with color: UIColor, amount: CGFloat) -> UIColor {
            var red1: CGFloat = 0
            var green1: CGFloat = 0
            var blue1: CGFloat = 0
            var alpha1: CGFloat = 0
    
            var red2: CGFloat = 0
            var green2: CGFloat = 0
            var blue2: CGFloat = 0
            var alpha2: CGFloat = 0
    
            getRed(&red1, green: &green1, blue: &blue1, alpha: &alpha1)
            color.getRed(&red2, green: &green2, blue: &blue2, alpha: &alpha2)
    
            return UIColor(
                red: red1 * (1.0 - amount) + red2 * amount,
                green: green1 * (1.0 - amount) + green2 * amount,
                blue: blue1 * (1.0 - amount) + blue2 * amount,
                alpha: alpha1
            )
        }
    }
    

    Here are examples with some colors

提交回复
热议问题