ios - 将淡入淡出效果应用于 UICollectionView 的顶部和底部

标签 ios swift uicollectionview calayer

我已经阅读了这里的示例,但我无法按照我想要的方式进行操作,不知何故,我的渐变示例卡在屏幕中间,无法按预期工作。

我有一个 UICollectionView,它通过垂直滚动填充整个屏幕。

我希望 UICollectionView 的顶部和底部为黑色,中间为透明(因为我使用的是黑色 blackgroundColor)。

我尝试应用渐变,但不知何故我无法实现我想要的。

这是我的代码:

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

上面的代码将渐变放置在屏幕中间,但相反。如果淡入全黑,则屏幕顶部和底部以及中间部分是透明的。

我正在尝试创建这样的东西:

img

感谢您的帮助

最佳答案

您可以通过更改颜色线来实现这一点:

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

或者,如果您想更好地控制渐变,您也可以使用下面的代码并调整位置和/或颜色 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

文档中的原因;

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.

关于ios - 将淡入淡出效果应用于 UICollectionView 的顶部和底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51643932/

相关文章:

ios - 未从 Collection View 调用 prepareForSegue

ios - 在 IBAction 按钮上加载插页式广告

ios - 如何将 NSString 转换为 const void

c++ - Xcode 8、Swift 和 C++

ios - 我如何使用 swift 2.3 项目支持 iOS 版本 10.3

Swift 可选的 inout 参数和 nil

当标题在屏幕上时,IOS UICollectionView insertItemsAtIndexPaths 崩溃

ios - CNContact 最后修改日期和联系人已更改

objective-c - objective-c 中的 Swift 全局变量和全局函数

ios - 从 UICollectionView 可见区域创建 UIImage