在 Swift 中的视图上添加渐变

Add Gradient on a view in Swift

以下代码似乎可以使用 Objective-C,但它的 Swift 版本不起作用。

我试过以下方法:

试试这个:

var mGradient : CAGradientLayer = CAGradientLayer()
mGradient.frame = favoriteCell.mImageView.bounds
mGradient.frame.origin = CGPointMake(0.0,0.0)

var colors = [CGColor]()
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 1).CGColor)
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 0).CGColor)

mGradient.locations = [0.0 , 1.0]
mGradient.startPoint = CGPointMake(0.1, 0.5)
mGradient.endPoint = CGPointMake(0.9, 0.5)
mGradient.frame = CGRect(x: 0.0, y: 0.0, width: favoriteCell.mImageView.frame.size.width, height: favoriteCell.mImageView.frame.size.height)

favoriteCell.mImageView.layer.insertSublayer(mGradient, atIndex: 0)

您需要设置渐变的颜色

mGradient.colors = colors

Swift 3

let mGradient = CAGradientLayer()
mGradient.frame = favoriteCell.mImageView.bounds
var colors = [CGColor]()
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor)
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 0).cgColor)

mGradient.startPoint = CGPoint(x: 0.1, y: 0.5)
mGradient.endPoint = CGPoint(x: 0.9, y: 0.5)
mGradient.colors = colors

favoriteCell.mImageView.layer.addSublayer(mGradient)