简体   繁体   中英

Apply fade effect to top and bottom of UICollectionView

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM