skip to Main Content

I’ve created a vertical gradient (black to white) as a mask layer for an UIImageView, but the linear fade is not working for me.

I want to show more of the full-alpha image and fade quicker towards the bottom, so I was thinking an exponential curve is what I’m looking for. I’d really like to avoid manually adding extra colors/locations, as it will look pretty choppy.

Is there any way to achieve this?

Edit: here’s the difference
enter image description here
As you can see, there’s a lot less black in the exponential one.

2

Answers


  1. Chosen as BEST ANSWER

    I ended up writing my own function, settling on a easeInOutCubic:

    let equation: ((Double)->Double) = { x in
        //ease in out cubic
        return x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2
    }
    
    var colors: [CGColor] = []
    var locations: [NSNumber] = []
    let min: Double = 0
    let max: Double = 1
    let steps: Double = 30
    
    for i in stride(from: min, through: max, by: max/steps)
    {
        let alpha = 1 - equation(i)
        let location = NSNumber(value: i)
    
        colors.append(UIColor.black.withAlphaComponent(alpha).cgColor)
        locations.append(location)
    }
        
    //assign colors/locations to new gradient layer
    myGradientLayer = CAGradientLayer()
    myGradientLayer.frame = bounds
    myGradientLayer.colors = colors
    myGradientLayer.locations = locations
    
    //assign gradient layer as mask
    layer.mask = myGradientLayer
    

  2. There’s no built in way to do that with CAGradientLayer. Sadly! I’ve wanted it too.

    Have you tried adding lots of stops? That’s probably what you want to do. Don’t think of it as manually adding stops, and don’t do it by hand. Instead, think of it as writing a custom easing function for your gradient. You should be able to get things looking good.

    I haven’t used these, but there are at least a couple of older projects on GitHub that might provide a starting point:

    https://github.com/hoteltonight/HTGradientEasing
    https://github.com/janselv/smooth-gradient

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search