iOS UIImageView 顶部渐变为黑色

9
我有一个UITableView,其中我的单元格backgroundView是一个UIImageView。我希望每个图像的顶部渐变为黑色,以便我可以叠加一些白色文本。
我已经查看了一些答案,比如this,但似乎都不起作用。
tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)中,我尝试过:
var imageView = UIImageView(image: image)

var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = imageView.frame
gradient.colors = [UIColor.blackColor(), UIColor.clearColor()]
gradient.locations = [0.0, 0.1]
imageView.layer.insertSublayer(gradient, atIndex: 0)

cell!.backgroundView = imageView

但我看不到渐变效果,删除渐变代码后也没有区别。我的渐变是在图片下面吗?
如果我用imageView.layer.mask = gradient替换imageView.layer.insertSublayer(gradient, atIndex: 0)这行代码,那么我的单元格只会是空白和白色(没有图片了)。

1
我是您所链接答案的发布者。请注意,gradient.colors 应该包含 CGColor 而不是 UIColor - duci9y
1
恭喜达成3k ;) - jezrael
3个回答

9
在你的gradient.colors中,需要有一个CGColor数组,因此:
gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]

哦,他在使用UIColors,是吗?很好的发现。我没注意到。 - Duncan C

3

对于Swift 3.0,需要进行一些小的调整:

    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = imageView.frame
    gradient.colors = [UIColor.black.cgColor, UIColor.clear.cgColor]
    gradient.locations = [0.0, 0.1]
    imageView.layer.insertSublayer(gradient, at: 0)

3

我忘记了层数组的排序方式。不过,你应该使用addSubLayer将渐变图层添加到图像视图的图层顶部,而不是使用insertSublayer:atIndex:方法。你希望渐变图层位于其他图层的顶部,这样它的非不透明部分才能覆盖图像视图。


使用被接受回答中提到的 CGColor 修复,两个方法都适用于我,但是 addSubLayer 显然更加简单直接。 - Imran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接