简体   繁体   English

将淡化效果应用于UICollectionView的顶部和底部

[英]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. 我有一个UICollectionView用垂直滚动填充整个屏幕。

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). 我希望UICollectionView的顶部和底部是黑色的,中间是透明的(因为我使用的是blackblackgroundColor)。

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: 或者,如果您想进一步控制渐变,还可以使用下面的代码并尝试使用位置和/或颜色alpha值:

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. 一个可选的图层,其Alpha通道用于掩盖该图层的内容。

The layer's alpha channel determines how much of the layer's content and background shows through. 图层的Alpha通道确定显示多少图层内容和背景。 Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content. 完全或部分不透明的像素允许基础内容通过显示,但完全透明的像素会阻止该内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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