我有这个扩展,在Swift中为一个视图添加一个渐变:
extension UIView { func addGradientWithColor(colorTop: UIColor, colorButton: UIColor){ let gradient = CAGradientLayer() gradient.frame = self.bounds gradient.colors = [colorTop.cgColor, colorButton.cgColor] self.layer.insertSublayer(gradient, at: 0) } }
然后,我在我的UIViewController中使用它:
override func viewDidLoad(){ self.view.addGradientWithColor(colorTop: UIColor.red, colorButton: UIColor.clear) super.viewDidLoad() }
我运行模拟器,效果很好.但是,当我想在真实设备上使用我的应用程序时,Gradient不起作用.
PD:我尝试了许多方法来做一个Gradient,但在真实设备上没有任何效果.
问题是当视图大小发生变化时,您没有调整图层大小,因此它保持在初始值,这主要取决于视图的创建方式.
我建议使用UIView
子类,并更新方法中的图层大小,layoutSubviews
在视图调整大小时始终会调用它:
@IBDesignable open class GradientView: UIView { @IBInspectable public var startColor: UIColor = .white { didSet { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] setNeedsDisplay() } } @IBInspectable public var endColor: UIColor = .white { didSet { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] setNeedsDisplay() } } private lazy var gradientLayer: CAGradientLayer = { let gradientLayer = CAGradientLayer() gradientLayer.frame = self.bounds gradientLayer.colors = [self.startColor.cgColor, self.endColor.cgColor] return gradientLayer }() override init(frame: CGRect) { super.init(frame: frame) layer.insertSublayer(gradientLayer, at: 0) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.insertSublayer(gradientLayer, at: 0) } open override func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = bounds } }
上面的代码也让你调整Xcode的开始和结束颜色,这样你就可以估计部署时视图的样子.
试试这个,它对我有用.码:
let gradientLayer:CAGradientLayer = CAGradientLayer() gradientLayer.frame.size = self.gradientView.frame.size gradientLayer.colors = [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] //Use diffrent colors gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0) gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0) self.gradientView.layer.addSublayer(gradientLayer)
有关详细说明,请参阅:渐变在UIView上