如何在CollectionView单元格内向图像添加渐变层

时间:2019-02-19 07:12:44

标签: swift cagradientlayer

我具有包含ImageViews和标签的自定义Collection View单元。我想为图像视图添加渐变色。

我尝试了所有可能的解决方案,例如为图像的子层添加蒙版和添加渐变。但是没有任何效果,请指导我解决此问题

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.asanasImage.layer.bounds
    gradientLayer.colors = [UIColor.clear.cgColor,UIColor.black.cgColor]
    gradientLayer.locations = [0.7,1.2]
    self.asanasImage.layer.addSublayer(gradientLayer)

1 个答案:

答案 0 :(得分:1)

嗨!尝试在方法

中为imageView设置渐变

cellForItemAt(_ indexpath: IndexPath)方法在集合“查看单元格”中。

使用此方法

func setGradientBackground(imageView: UIImageView, colorTop: UIColor, colorBottom: UIColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.locations = [0, 1]
        gradientLayer.frame = self.view.bounds
        imageView.layer.insertSublayer(gradientLayer, at: 0)
    }

最后在cellForItemAt(_ indexpath: IndexPath)内像这样设置imageView的渐变

setGradientBackground(imageView: cell.your_image_View, colorTop: any_color, colorBottom: any_color)

根据您的需要和渐变色选择自定义方法。

希望我能够提供帮助。如果它有效,请知道并投票!谢谢:D

相关问题