Apply fade effect to top and bottom of UICollectio

2019-02-20 04:19发布

I've read examples around here but I cannot do it the way I desire, somehow my gradient examples are stuck on the middle of the screen, not working as expected.

I have a UICollectionView which fills the whole screen with vertical scroll.

I want the top and bottom of the UICollectionView to be black and the middle to be transparent (since I'm using a black blackgroundColor).

I tried to apply gradients, but somehow I'm failing to accomplish what I want.

Here's my code:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.black.cgColor, UIColor.clear.cgColor, UIColor.black.cgColor]
gradient.startPoint = CGPoint(x: 1, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
view.layer.mask = gradient

The code above is placing the gradient in the middle of the screen but inverted. It is transparent on top and bottom of the screen and the middle section if fading to complete black.

I'm trying to create something like this:

img

Thanks for helping

1条回答
SAY GOODBYE
2楼-- · 2019-02-20 04:56

You can achieve that by changing your color line with this:

gradient.colors = [
    UIColor(white: 1.0, alpha: 0).cgColor,
    UIColor(white: 1.0, alpha: 1).cgColor,
    UIColor(white: 1.0, alpha: 0).cgColor
]

Or if you want to have even more control over your gradient, you can also use the code below and play around with the location and/or color alpha values:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [
    UIColor(white: 1, alpha: 0).cgColor,
    UIColor(white: 1, alpha: 1).cgColor,
    UIColor(white: 1, alpha: 1).cgColor,
    UIColor(white: 1, alpha: 0).cgColor
]
gradient.locations = [0, 0.4, 0.6, 1]
view.layer.mask = gradient

Reason of this from the documentation;

An optional layer whose alpha channel is used to mask the layer’s content.

The layer’s alpha channel determines how much of the layer’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.

查看更多
登录 后发表回答