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


184

我正在尝试将渐变用作视图(情节提要的主视图)的背景颜色。该代码运行,但没有任何变化。我正在使用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)
      }
    }
  }

1
我发布了一个使它变得简单的组件,您可以使用可可豆荚来使用它,我建议您这样做,因为它非常简单,您可以通过XCode上的界面生成器进行设置。查看更多github.com/heuristisk/hkGraddiant
Anderson

Answers:


159

您要提供给渐变的颜色必须为类型CGColor。因此,将您的数组设置CGColorgl.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]
    }
}

17
这是关键:gl.frame = view.bounds;
justingordon 2014年

2
fatal error: array element cannot be bridged to Objective-C分配给.colors属性时出现此错误。这可能是什么问题?
Tricertops 2014年

3
我已经解决了。这是斯威夫特的错误,只是存储在显式类型变量数组[AnyObject],并随后将其分配给.colors属性。
三角龙

1
令c:数组<AnyObject> = [colorTop,colorBottom]
JP_14年

7
迅速1.0的语法将是let c: [AnyObject] = [colorTop, colorBottom]
克里斯

191

Xcode 11•Swift 5.1


您可以如下设计自己的渐变视图:

@IBDesignable
public class Gradient: 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 public class var layerClass: AnyClass { CAGradientLayer.self }

    var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

    func updatePoints() {
        if horizontalMode {
            gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
        } else {
            gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
        }
    }
    func updateLocations() {
        gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
    }
    func updateColors() {
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
    }
    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updatePoints()
        updateLocations()
        updateColors()
    }

}

在此处输入图片说明


1
不要忘了导入UIKit
djdance

您能解释一下这一行吗:覆盖类var layerClass:AnyClass {return CAGradientLayer.self}
Mostafa Mohamed Raafat


可以使用的最大位置/位置/渐变挡数是多少?似乎超过一定数量,iOS无法呈现渐变。页面为空
阿伦·普拉萨德

1
@AsadAmodi谢谢
Leo Dabus

80

而且,如果您需要更改渐变的方向,则必须使用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, at: 0)

4
您可能会遇到的问题之一是,当您添加子层时,它可能位于所有其他项目,标签,图像等之上。要解决此问题,请创建位于所有内容之下的另一个视图,并将其约束设置为容器的约束您需要渐变色。然后设置要应用于此视图的渐变色。然后,子视图将插入到该层中,而不位于其他任何位置上。
米卡蒙托亚

74

只需修改上述答案即可。

在此处输入图片说明

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, at:0)
}

然后在内部调用此方法 viewWillAppear

override func viewWillAppear(_ animated: Bool) {
    setGradientBackground()
    super.viewWillAppear(animated)
}

在此处输入图片说明


1
这在现有元素上放置了一层,所以我什么也看不到。有什么建议?
JamesG'9

19
替换self.view.layer.addSublayer(gradientLayer)self.view.layer.insertSublayer(gradientLayer, at: 0),这会将图层置于所有其他图层“下方”
WMR

有没有办法消除这种渐变效果?喜欢删除功能吗?
泰勒·鲁特

太棒了... !!!!
Yash Bedi

22

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)

}

5
梯度。起始点= CGPoint(x:0.0,y:1.0)梯度.endPoint = CGPoint(x:1.0,y:1.0)用于不同的梯度位置。
PanMluvčí16年

colorWithAlphaComponent已重命名为withAlphaComponent
etayluz

20

我做了一个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)
    }
}       

7
我可能会误会,但最好让用户将颜色数组传递给该函数,而不是对其进行硬编码(除非您始终希望应用相同的渐变)。

3
CGPointMake(0.0,0.0)可以替换CGPointZero为简洁
JSmyth

17

我有这些扩展名:

@IBDesignable class GradientView: UIView {
    @IBInspectable var firstColor: UIColor = UIColor.red
    @IBInspectable var secondColor: UIColor = UIColor.green

    @IBInspectable var vertical: Bool = true

    lazy var gradientLayer: CAGradientLayer = {
        let layer = CAGradientLayer()
        layer.colors = [firstColor.cgColor, secondColor.cgColor]
        layer.startPoint = CGPoint.zero
        return layer
    }()

    //MARK: -

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        applyGradient()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        applyGradient()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        applyGradient()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        updateGradientFrame()
    }

    //MARK: -

    func applyGradient() {
        updateGradientDirection()
        layer.sublayers = [gradientLayer]
    }

    func updateGradientFrame() {
        gradientLayer.frame = bounds
    }

    func updateGradientDirection() {
        gradientLayer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
    }
}

@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 {
        didSet {
            updateGradientDirection()
        }
    }

    lazy var gradientLayer: CAGradientLayer = {
        let layer = CAGradientLayer()
        layer.colors = [firstColor.cgColor, secondColor.cgColor, thirdColor.cgColor]
        layer.startPoint = CGPoint.zero
        return layer
    }()

    //MARK: -

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        applyGradient()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        applyGradient()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        applyGradient()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        updateGradientFrame()
    }

    //MARK: -

    func applyGradient() {
        updateGradientDirection()
        layer.sublayers = [gradientLayer]
    }

    func updateGradientFrame() {
        gradientLayer.frame = bounds
    }

    func updateGradientDirection() {
        gradientLayer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
    }
}

@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
    }
}

用法:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明


最好不要在设置时在drawRect中添加图层
Fattie

1
将此添加到我的VC视图中将阻止所有操作。所有元素都隐藏在渐变下。怎么
回事

1
更改self.layer.addSublayer(layer)self.layer.insertSublayer(layer, at: 0)似乎可以防止渐变混淆界面生成器中的所有内容(至少在我的一项测试中如此)
S.Walker

15

试试这个,对我有用

  var gradientView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 35))
  let gradientLayer:CAGradientLayer = CAGradientLayer()
  gradientLayer.frame.size = self.gradientView.frame.size
  gradientLayer.colors = 
  [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] 
  //Use diffrent colors
  gradientView.layer.addSublayer(gradientLayer)

在此处输入图片说明

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

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

在此处输入图片说明

有关更多详细说明,请参阅最佳答案,或者您可以按照 Apple的CAGradientLayer

希望这对某些人有帮助。


使用以下选项,startPoint以及endPoint从左到右的渐变: gradient.startPoint = CGPoint(x: 0.0, y: 0.5) gradient.endPoint = CGPoint(x: 1.0, y: 0.5)以及从上到下: gradient.startPoint = CGPoint(x: 0.5, y: 0.0) gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
Nij

8

扩展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()]


结果

在此处输入图片说明


您不致电有任何特殊原因super.drawRect()吗?
拉斐尔'16

@Bearwithme号 应该可以正常工作super.drawRect()了。
迈克尔

最好将其添加到GradientView.swift的顶部:@IBInspectable var topColor: UIColor = UIColor.lightGrayColor() @IBInspectable var bottomColor: UIColor = UIColor.blueColor()然后您可以在设置中看到属性编辑器
德米特里·塞纳申科

8

这很容易

    // MARK: - Gradient
extension CAGradientLayer {
    enum Point {
        case topLeft
        case centerLeft
        case bottomLeft
        case topCenter
        case center
        case bottomCenter
        case topRight
        case centerRight
        case bottomRight
        var point: CGPoint {
            switch self {
            case .topLeft:
                return CGPoint(x: 0, y: 0)
            case .centerLeft:
                return CGPoint(x: 0, y: 0.5)
            case .bottomLeft:
                return CGPoint(x: 0, y: 1.0)
            case .topCenter:
                return CGPoint(x: 0.5, y: 0)
            case .center:
                return CGPoint(x: 0.5, y: 0.5)
            case .bottomCenter:
                return CGPoint(x: 0.5, y: 1.0)
            case .topRight:
                return CGPoint(x: 1.0, y: 0.0)
            case .centerRight:
                return CGPoint(x: 1.0, y: 0.5)
            case .bottomRight:
                return CGPoint(x: 1.0, y: 1.0)
            }
        }
    }
    convenience init(start: Point, end: Point, colors: [CGColor], type: CAGradientLayerType) {
        self.init()
        self.startPoint = start.point
        self.endPoint = end.point
        self.colors = colors
        self.locations = (0..<colors.count).map(NSNumber.init)
        self.type = type
    }
}

像这样使用:

let fistColor = UIColor.white
let lastColor = UIColor.black
let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: [fistColor.cgColor, lastColor.cgColor], type: .radial)
gradient.frame = yourView.bounds
yourView.layer.addSublayer(gradient)

投票枚举点
TA Truhoada

5

该代码将与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]
    }
}

@Blahji可以分享用法示例吗?并与UILabel
配合

将子图层插入UILabel会隐藏文本,因此,获得所需内容的最佳方法是将标签和渐变图层添加到UIView。
Balaji Malliswamy

5

斯威夫特4

添加视图插座

@IBOutlet weak var gradientView: UIView!

向视图添加渐变

func setGradient() {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor, UIColor.blue.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 = gradientView.layer.frame
    gradientView.layer.insertSublayer(gradient, at: 0)
}

1
如果gradientView.layer.frame不在(0,0),则渐变层将移位。我建议使用gradientView.layer.bounds。
vedrano

3

如果要使用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]
    }
}

之后,在视图控制器中,在类下实例化您的“ Color”类,如下所示:

let colors = Colors()

添加新功能:

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


3

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)

spritekitnode和cagradientlayer的性能如何?必须渲染图像似乎会比较慢。
μολὼν.λαβέ

我不知道该怎么做,但通常ca **类的性能要比Sprite Kit中的类高得多。
texuf

2

使用以下代码:

extension UIView {
func applyGradient(colours: [UIColor]) -> Void {
 let gradient: CAGradientLayer = CAGradientLayer()
 gradient.frame = self.bounds
 gradient.colors = colours.map { $0.cgColor }
 gradient.startPoint = CGPoint(x : 0.0, y : 0.5)
 gradient.endPoint = CGPoint(x :1.0, y: 0.5)
 self.layer.insertSublayer(gradient, at: 0)
 }
}

像这样调用此函数:

  self.mainView.applyGradient(colours: [.green, .blue])

1

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

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)

1

这是在可重用的Util类文件中进行设置的一种变体

在您的Xcode项目中:

  1. 创建一个新的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对功能代码的回答


1

快速将CAGradientLayer应用于任何对象(水平和垂直)

func makeGradientColor(`for` object : AnyObject , startPoint : CGPoint , endPoint : CGPoint) -> CAGradientLayer {
    let gradient: CAGradientLayer = CAGradientLayer()

    gradient.colors = [(UIColor(red: 59.0/255.0, green: 187.0/255.0, blue: 182.0/255.0, alpha: 1.00).cgColor), (UIColor(red: 57.0/255.0, green: 174.0/255.0, blue: 236.0/255.0, alpha: 1.00).cgColor)]
    gradient.locations = [0.0 , 1.0]

    gradient.startPoint = startPoint
    gradient.endPoint = endPoint
    gradient.frame = CGRect(x: 0.0, y: 0.0, width: object.frame.size.width, height: object.frame.size.height)
    return gradient
}

如何使用

let start : CGPoint = CGPoint(x: 0.0, y: 1.0)
let end : CGPoint = CGPoint(x: 1.0, y: 1.0)
let gradient: CAGradientLayer = self.makeGradientColor(for: vwTop, startPoint: start, endPoint: end)
vwTop.layer.insertSublayer(gradient, at: 0)

let start1 : CGPoint = CGPoint(x: 1.0, y: 1.0)
let end1 : CGPoint = CGPoint(x: 1.0, y: 0.0)
let gradient1: CAGradientLayer = self.makeGradientColor(for: vwTop, startPoint: start1, endPoint: end1)
vwBottom.layer.insertSublayer(gradient1, at: 0)

您可以在这里检查输出


1

我想为视图添加渐变,然后使用自动布局将其锚定。

    class GradientView: UIView {

    private let gradient: CAGradientLayer = {
        let layer = CAGradientLayer()
        let topColor: UIColor = UIColor(red:0.98, green:0.96, blue:0.93, alpha:0.5)
        let bottomColor: UIColor = UIColor.white
        layer.colors = [topColor.cgColor, bottomColor.cgColor]
        layer.locations = [0,1]
        return layer
    }()

    init() {
        super.init(frame: .zero)
        gradient.frame = frame
        layer.insertSublayer(gradient, at: 0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradient.frame = bounds

    }
}

1

要将渐变添加到图层,请添加:

let layer = CAGradientLayer()
layer.frame = CGRect(x: 64, y: 64, width: 120, height: 120)
layer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
view.layer.addSublayer(layer)

请也添加一些解释。
surajs1n

0

这是一个快速扩展,您可以在其中传递任意数量的任意颜色。它将在插入一个渐变之前删除所有以前的渐变,并且如果需要,它将返回新插入的渐变层以进行进一步处理:

    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
    }
}

0

允许您将任何内容传递UIColorGradientLayer类实例的更干净的代码:

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]
    }
}

0

在Swift 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.addGradienBorder(color: UIColor.black, opacity: 0.1, offset: CGSize(width:2 , height: 5), radius: 3, viewCornerRadius: 3.0)

0

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

  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)
    }
}

0

有一个名为Chameleon(https://github.com/viccalexander/Chameleon)的库,可用于渐变颜色。它甚至具有要实现的渐变样式。这是您如何在swift 4 podfile pod'ChameleonFramework / Swift'中添加它的方法:git =>' https://github.com/ViccAlexander/Chameleon.git',:branch =>'wip / swift4'

import ChameleonFramework

let colors:[UIColor] = [
  UIColor.flatPurpleColorDark(), 
  UIColor.flatWhiteColor()
]
view.backgroundColor = GradientColor(.TopToBottom, frame: view.frame, colors: colors)

0

对于那些想要答案的Objective C版本的人。经过测试并在iOS13上运行

// Done here so that constraints have completed and the frame is correct.
- (void) viewDidLayoutSubviews { 
    [super viewDidLayoutSubviews];
    UIColor *colorTop = [UIColor colorWithRed:(CGFloat)192.0/255.0 green: 38.0/255.0 blue: 42.0/255.0 alpha:1.0];
    UIColor *colorBottom = [UIColor colorWithRed: 35.0/255.0 green: 2.0/255.0 blue: 2.0/255.0 alpha: 1.0];
    CAGradientLayer *gl = [CAGradientLayer new];
    [gl setColors:@[(id)[colorTop CGColor], (id)[colorBottom CGColor]]];
    [gl setLocations:@[@0.0f, @1.0f]];
    self.view.backgroundColor = [UIColor clearColor];
    CALayer *backgroundLayer = gl;
    backgroundLayer.frame = self.view.frame;
    [self.view.layer insertSublayer:backgroundLayer atIndex:0];
}

0

我注意到的一件事是,您必须在不清除文本的情况下向UILabel添加渐变。一种简单的解决方法是使用UIButton并禁用用户交互。


0

SwiftUI:您可以将LinearGradientstruct用作中的第一个元素ZStack。作为的“底部” ZStack,它将作为背景色。AngularGradient并且RadialGradient也可用。

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom)
                .edgesIgnoringSafeArea(.all)
            // Put other content here; it will appear on top of the background gradient
        }
    }
}

0

我混合了Rohit SisodiaMGM的答案

// MARK: - Gradient

public enum CAGradientPoint {
    case topLeft
    case centerLeft
    case bottomLeft
    case topCenter
    case center
    case bottomCenter
    case topRight
    case centerRight
    case bottomRight
    var point: CGPoint {
        switch self {
        case .topLeft:
            return CGPoint(x: 0, y: 0)
        case .centerLeft:
            return CGPoint(x: 0, y: 0.5)
        case .bottomLeft:
            return CGPoint(x: 0, y: 1.0)
        case .topCenter:
            return CGPoint(x: 0.5, y: 0)
        case .center:
            return CGPoint(x: 0.5, y: 0.5)
        case .bottomCenter:
            return CGPoint(x: 0.5, y: 1.0)
        case .topRight:
            return CGPoint(x: 1.0, y: 0.0)
        case .centerRight:
            return CGPoint(x: 1.0, y: 0.5)
        case .bottomRight:
            return CGPoint(x: 1.0, y: 1.0)
        }
    }
}

extension CAGradientLayer {

    convenience init(start: CAGradientPoint, end: CAGradientPoint, colors: [CGColor], type: CAGradientLayerType) {
        self.init()
        self.frame.origin = CGPoint.zero
        self.startPoint = start.point
        self.endPoint = end.point
        self.colors = colors
        self.locations = (0..<colors.count).map(NSNumber.init)
        self.type = type
    }
}

extension UIView {

    func layerGradient(startPoint:CAGradientPoint, endPoint:CAGradientPoint ,colorArray:[CGColor], type:CAGradientLayerType ) {
        let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: colorArray, type: type)
        gradient.frame.size = self.frame.size
        self.layer.insertSublayer(gradient, at: 0)
    }
}

要使用写:-

        btnUrdu.layer.cornerRadius = 25
        btnUrdu.layer.masksToBounds = true 
        btnUrdu.layerGradient(startPoint: .centerRight, endPoint: .centerLeft, colorArray: [UIColor.appBlue.cgColor, UIColor.appLightBlue.cgColor], type: .axial)

输出:

输出

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.