如何将渐变应用于iOS Swift应用的背景视图

我试图应用渐变作为视图的背景颜色(故事板的主视图)。 代码运行,但没有任何变化。 我正在使用xCode Beta 2和Swift。

代码如下:

class Colors { let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0) let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0) let gl: CAGradientLayer init() { gl = CAGradientLayer() gl.colors = [ colorTop, colorBottom] gl.locations = [ 0.0, 1.0] } } 

那么在视图控制器中:

  let colors = Colors() func refresh() { view.backgroundColor = UIColor.clearColor() var backgroundLayer = colors.gl backgroundLayer.frame = view.frame view.layer.insertSublayer(backgroundLayer, atIndex: 0) } } } 

您要为渐变提供的颜色必须是CGColortypes。 所以把你的CGColor数组设置为gl.colors

正确的代码是:

 class Colors { var gl:CAGradientLayer! init() { let colorTop = UIColor(red: 192.0 / 255.0, green: 38.0 / 255.0, blue: 42.0 / 255.0, alpha: 1.0).cgColor let colorBottom = UIColor(red: 35.0 / 255.0, green: 2.0 / 255.0, blue: 2.0 / 255.0, alpha: 1.0).cgColor self.gl = CAGradientLayer() self.gl.colors = [colorTop, colorBottom] self.gl.locations = [0.0, 1.0] } } 

Xcode 8.2•Swift 3.0.2


你可以devise你自己的渐变视图如下:

 @IBDesignable class GradientView: UIView { @IBInspectable var startColor: UIColor = .black { didSet { updateColors() }} @IBInspectable var endColor: UIColor = .white { didSet { updateColors() }} @IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }} @IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }} @IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }} @IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }} override class var layerClass: AnyClass { return CAGradientLayer.self } var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } func updatePoints() { if horizontalMode { gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5) } else { gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0) gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1) } } func updateLocations() { gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] } func updateColors() { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] } override func layoutSubviews() { super.layoutSubviews() updatePoints() updateLocations() updateColors() } } 

在这里输入图像说明

如果你需要改变渐变的方向,你必须使用startPoint和endPoint。

 let gradient: CAGradientLayer = CAGradientLayer() gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor] gradient.locations = [0.0 , 1.0] gradient.startPoint = CGPoint(x: 0.0, y: 1.0) gradient.endPoint = CGPoint(x: 1.0, y: 1.0) gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height) self.view.layer.insertSublayer(gradient, atIndex: 0) 

只是修改上面提到的答案。

在这里输入图像说明

 func setGradientBackground() { let colorTop = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).CGColor let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).CGColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ colorTop, colorBottom] gradientLayer.locations = [ 0.0, 1.0] gradientLayer.frame = self.view.bounds self.view.layer.insertSublayer(gradientLayer) } 

在这里输入图像说明

我做了一个UIView扩展应用一个基本的渐变到任何视图

 extension UIView { func layerGradient() { let layer : CAGradientLayer = CAGradientLayer() layer.frame.size = self.frame.size layer.frame.origin = CGPointMake(0.0,0.0) layer.cornerRadius = CGFloat(frame.width / 20) let color0 = UIColor(red:250.0/255, green:250.0/255, blue:250.0/255, alpha:0.5).CGColor let color1 = UIColor(red:200.0/255, green:200.0/255, blue: 200.0/255, alpha:0.1).CGColor let color2 = UIColor(red:150.0/255, green:150.0/255, blue: 150.0/255, alpha:0.1).CGColor let color3 = UIColor(red:100.0/255, green:100.0/255, blue: 100.0/255, alpha:0.1).CGColor let color4 = UIColor(red:50.0/255, green:50.0/255, blue:50.0/255, alpha:0.1).CGColor let color5 = UIColor(red:0.0/255, green:0.0/255, blue:0.0/255, alpha:0.1).CGColor let color6 = UIColor(red:150.0/255, green:150.0/255, blue:150.0/255, alpha:0.1).CGColor layer.colors = [color0,color1,color2,color3,color4,color5,color6] self.layer.insertSublayer(layer, atIndex: 0) } } 

Swift3中试试这个:

  func addGradient(){ let gradient:CAGradientLayer = CAGradientLayer() gradient.frame.size = self.viewThatHoldsGradient.frame.size gradient.colors = [UIColor.white.cgColor,UIColor.white.withAlphaComponent(0).cgColor] //Or any colors self.viewThatHoldsGradient.layer.addSublayer(gradient) } 

用这个自定义类扩展UIView


GradientView.swift

 import UIKit class GradientView: UIView { // Default Colors var colors:[UIColor] = [UIColor.redColor(), UIColor.blueColor()] override func drawRect(rect: CGRect) { // Must be set when the rect is drawn setGradient(colors[0], color2: colors[1]) } func setGradient(color1: UIColor, color2: UIColor) { let context = UIGraphicsGetCurrentContext() let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [color1.CGColor, color2.CGColor], [0, 1])! // Draw Path let path = UIBezierPath(rect: CGRectMake(0, 0, frame.width, frame.height)) CGContextSaveGState(context) path.addClip() CGContextDrawLinearGradient(context, gradient, CGPointMake(frame.width / 2, 0), CGPointMake(frame.width / 2, frame.height), CGGradientDrawingOptions()) CGContextRestoreGState(context) } override func layoutSubviews() { // Ensure view has a transparent background color (not required) backgroundColor = UIColor.clearColor() } } 

用法

gradientView.colors = [UIColor.blackColor().colorWithAlphaComponent(0.8), UIColor.clearColor()]


结果

在这里输入图像说明

此代码将与Swift 3.0一起使用

 class GradientView: UIView { override open class var layerClass: AnyClass { get{ return CAGradientLayer.classForCoder() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let gradientLayer = self.layer as! CAGradientLayer let color1 = UIColor.white.withAlphaComponent(0.1).cgColor as CGColor let color2 = UIColor.white.withAlphaComponent(0.9).cgColor as CGColor gradientLayer.locations = [0.60, 1.0] gradientLayer.colors = [color2, color1] } } 

我有这些扩展名:

 @IBDesignable class GradientView: UIView { @IBInspectable var firstColor: UIColor = UIColor.red @IBInspectable var secondColor: UIColor = UIColor.green @IBInspectable var vertical: Bool = true override func awakeFromNib() { super.awakeFromNib() applyGradient() } func applyGradient() { let colors = [firstColor.cgColor, secondColor.cgColor] let layer = CAGradientLayer() layer.colors = colors layer.frame = self.bounds layer.startPoint = CGPoint(x: 0, y: 0) layer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0) self.layer.addSublayer(layer) } override func draw(_ rect: CGRect) { super.draw(rect) #if TARGET_INTERFACE_BUILDER applyGradient() #endif } } @IBDesignable class ThreeColorsGradientView: UIView { @IBInspectable var firstColor: UIColor = UIColor.red @IBInspectable var secondColor: UIColor = UIColor.green @IBInspectable var thirdColor: UIColor = UIColor.blue @IBInspectable var vertical: Bool = true override func awakeFromNib() { super.awakeFromNib() applyGradient() } func applyGradient() { let colors = [firstColor.cgColor, secondColor.cgColor, thirdColor.cgColor] let layer = CAGradientLayer() layer.colors = colors layer.frame = self.bounds layer.startPoint = CGPoint(x: 0, y: 0) layer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0) self.layer.addSublayer(layer) } override func draw(_ rect: CGRect) { super.draw(rect) #if TARGET_INTERFACE_BUILDER applyGradient() #endif } } @IBDesignable class RadialGradientView: UIView { @IBInspectable var outsideColor: UIColor = UIColor.red @IBInspectable var insideColor: UIColor = UIColor.green override func awakeFromNib() { super.awakeFromNib() applyGradient() } func applyGradient() { let colors = [insideColor.cgColor, outsideColor.cgColor] as CFArray let endRadius = sqrt(pow(frame.width/2, 2) + pow(frame.height/2, 2)) let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil) let context = UIGraphicsGetCurrentContext() context?.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation) } override func draw(_ rect: CGRect) { super.draw(rect) #if TARGET_INTERFACE_BUILDER applyGradient() #endif } } 

用法:

在这里输入图像说明

在这里输入图像说明

在这里输入图像说明

如果要使用HEX而不是RGBA,只需拖放一个新的空.swift并添加下面提到的代码:

  import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = advance(rgba.startIndex, 1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (count(hex)) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { println("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } } 

同样,拖动另一个空的.swift文件,并添加下面提到的代码:

  class Colors { let colorTop = UIColor(rgba: "##8968CD").CGColor let colorBottom = UIColor(rgba: "#5D478B").CGColor let gl: CAGradientLayer init() { gl = CAGradientLayer() gl.colors = [ colorTop, colorBottom] gl.locations = [ 0.0, 1.0] } } 

之后,在视图控制器下,类实例化你的'颜色'类像这样:

 let colors = Colors() 

添加一个新的function:

 func refresh() { view.backgroundColor = UIColor.clearColor() var backgroundLayer = colors.gl backgroundLayer.frame = view.frame view.layer.insertSublayer(backgroundLayer, atIndex: 0) } 

在viewDidLoad中声明该函数:

 refresh() 

你完成了:))如果与RGBA相比,使用HEX就太简单了。 :d

Swift 3 – 仅使用纹理和SKSpriteNode,不需要UIView

 import Foundation import SpriteKit class GradientSpriteNode : SKSpriteNode { convenience init(size: CGSize, colors: [UIColor], locations: [CGFloat]) { let texture = GradientSpriteNode.texture(size: size, colors: colors, locations: locations) self.init(texture: texture, color:SKColor.clear, size: texture.size()) } private override init(texture: SKTexture!, color: SKColor, size: CGSize) { super.init(texture: texture, color: color, size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private static func texture(size: CGSize, colors: [UIColor], locations: [CGFloat]) -> SKTexture { UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext()! let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors.map{$0.cgColor} as CFArray, locations: locations)! context.drawLinearGradient(gradient, start: CGPoint(x: size.width / 2, y: 0), end: CGPoint(x: size.width / 2, y: size.height), options: CGGradientDrawingOptions()) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return SKTexture(image: image!) } } 

用法:

 let gradient = GradientSpriteNode( size: CGSize(width: 100, height: 100), colors: [UIColor.red, UIColor.blue], locations: [0.0, 1.0]) addChild(gradient) 

这是一个迅速的扩展,你可以通过任意数量的任意颜色。 它将在插入之前删除以前的任何渐变,并且如果需要,它将返回新插入的渐变图层以供进一步操作:

  extension UIView { /** Given an Array of CGColor, it will: - Remove all sublayers of type CAGradientLayer. - Create and insert a new CAGradientLayer. - Parameters: - colors: An Array of CGColor with the colors for the gradient fill - Returns: The newly created gradient CAGradientLayer */ func layerGradient(colors c:[CGColor])->CAGradientLayer { self.layer.sublayers = self.layer.sublayers?.filter(){!($0 is CAGradientLayer)} let layer : CAGradientLayer = CAGradientLayer() layer.frame.size = self.frame.size layer.frame.origin = CGPointZero layer.colors = c self.layer.insertSublayer(layer, atIndex: 0) return layer } } 

只需指定要显示渐变颜色的视图的框架。

 let firstColor = UIColor(red: 69/255, green: 90/255, blue: 195/255, alpha: 1.0).CGColor let secondColor = UIColor(red: 230/255, green: 44/255, blue: 75/255, alpha: 1.0).CGColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ firstColor, secondColor] gradientLayer.locations = [ 0.0, 1.0] gradientLayer.frame = CGRectMake(0, 0, 375, 64)// You can mention frame here self.view.layer.addSublayer(gradientLayer) 

更清晰的代码,可让您将任何UIColor传递给GradientLayer类的实例:

 class GradientLayer { let gradientLayer: CAGradientLayer let colorTop: CGColor let colorBottom: CGColor init(colorTop: UIColor, colorBottom: UIColor) { self.colorTop = colorTop.CGColor self.colorBottom = colorBottom.CGColor gradientLayer = CAGradientLayer() gradientLayer.colors = [colorTop, colorBottom] gradientLayer.locations = [0.0, 1.0] } } 

这里是一个可以在一个可重用的Util类文件中设置的变体

在你的Xcode项目中:

  1. 创build一个新的Swift类,调用它UI_Util.swift,并填充它,如下所示:

     import Foundation import UIKit class UI_Util { static func setGradientGreenBlue(uiView: UIView) { let colorTop = UIColor(red: 15.0/255.0, green: 118.0/255.0, blue: 128.0/255.0, alpha: 1.0).cgColor let colorBottom = UIColor(red: 84.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0).cgColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ colorTop, colorBottom] gradientLayer.locations = [ 0.0, 1.0] gradientLayer.frame = uiView.bounds uiView.layer.insertSublayer(gradientLayer, at: 0) } } 

  1. 现在你可以像这样调用任何ViewController的函数:

     class AbcViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() UI_Util.setGradientGreen(uiView: self.view) } 

感谢katwal-Dipak对function代码的回答

如果您有查看集合(多视图),请执行此操作

  func setGradientBackground() { let v:UIView for v in viewgradian //here viewgradian is your view Collection Outlet name { let layer:CALayer var arr = [AnyObject]() for layer in v.layer.sublayers! { arr.append(layer) } let colorTop = UIColor(red: 216.0/255.0, green: 240.0/255.0, blue: 244.0/255.0, alpha: 1.0).cgColor let colorBottom = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0).cgColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ colorBottom, colorTop] gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0) gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0) gradientLayer.frame = v.bounds v.layer.insertSublayer(gradientLayer, at: 0) } } 

易于使用的扩展在迅速3

 extension CALayer { func addGradienBorder(colors:[UIColor] = [UIColor.red,UIColor.blue], width:CGFloat = 1) { let gradientLayer = CAGradientLayer() gradientLayer.frame = CGRect(origin: .zero, size: self.bounds.size) gradientLayer.startPoint = CGPoint(x:0.0, y:0.5) gradientLayer.endPoint = CGPoint(x:1.0, y:0.5) gradientLayer.colors = colors.map({$0.cgColor}) let shapeLayer = CAShapeLayer() shapeLayer.lineWidth = width shapeLayer.path = UIBezierPath(rect: self.bounds).cgPath shapeLayer.fillColor = nil shapeLayer.strokeColor = UIColor.black.cgColor gradientLayer.mask = shapeLayer self.addSublayer(gradientLayer) } } 

使用你的看法,例如

 yourView.setShadowWithColor(color: UIColor.black, opacity: 0.1, offset: CGSize(width:2 , height: 5), radius: 3, viewCornerRadius: 3.0) 

试试这个,它为我工作,

  let gradientLayer:CAGradientLayer = CAGradientLayer() gradientLayer.frame.size = self.gradientView.frame.size gradientLayer.colors = [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] //Use diffrent colors self.gradientView.layer.addSublayer(gradientLayer) 

在这里输入图像说明

您可以添加渐变颜色的起点和终点。

  gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0) gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0) 

在这里输入图像说明

希望这是对某个人的帮助。