iOS 在 UIImageView 顶部淡化为黑色

标签 ios swift uiimageview cagradientlayer

我有一个 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.insertSublayer(gradient, atIndex: 0) 替换为 imageView.layer.mask = gradient 那么我的单元格只是空白和白色(不再有图像)。

最佳答案

在您的 gradient.colors 中,您需要有 CGColor 数组,所以:

gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]

关于iOS 在 UIImageView 顶部淡化为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31859263/

相关文章:

ios - 启动屏幕图像显示不正确

ios - 约束更改后 UITableView 水龙头第一次不工作

ios - 如果 https 服务器使用不安全的 SSL 证书托管,则限制 Web 服务调用

ios - 是否必须为 iPhone 应用程序选择设备作为通用?

ios - 在 ViewController 之外显示 UIAlertController

ios - 将 Viewcontroller 作为参数传递

iOS swift 使用选择器调用 Objective-C 方法失败

swift - 返回上一个 View Controller 时的 UIImage 问题

ios - 无法构建动态 NSURL 以将图像放入 UIImage

ios - CGImageCreateWithImageInRect 切断