web-dev-qa-db-fra.com

Comment appliquer le dégradé à la vue d'arrière-plan de l'application Swift iOS

J'essaie d'appliquer un dégradé comme couleur d'arrière-plan d'une vue (vue principale d'un storyboard). Le code s'exécute, mais rien ne change. J'utilise xCode Beta 2 et Swift.

Voici le code:

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

puis dans le contrôleur de vue:

  let colors = Colors()

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

Les couleurs que vous fournissez au dégradé doivent être de type CGColor. Définissez donc votre tableau de CGColor à gl.colors.

Le code correct est:

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]
    }
}
129
Yatheesha B L

Xcode 8.2 • Swift 3.0.2


Vous pouvez concevoir votre propre vue en dégradé comme suit:

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

 enter image description here

116
Leo Dabus

Et si vous devez changer la direction du dégradé, vous devez utiliser startPoint et 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)
61
gasho

Il suffit de modifier la réponse mentionnée ci-dessus.

 enter image description here

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

 enter image description here

47
katwal-Dipak

Dans Swift3 essayez ceci:

 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)

}
20
Zaid Pathan

J'ai créé une extension UIView pour appliquer un dégradé de base à n'importe quelle vue.

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

J'ai ces extensions:

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

Usage:

 enter image description here

 enter image description here

 enter image description here

14
ChikabuZ

Essayez ceci, ça marche pour moi,

  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)

 enter image description here

Vous pouvez ajouter des points de départ et d'arrivée de la couleur du dégradé.

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

 enter image description here

Pour plus de détails, voir Meilleure réponse ou vous pouvez suivre CAGradientLayer de Apple

Espoirs Ceci est une aide pour quelqu'un.

11
Jaywant Khedkar

Ce code fonctionnera avec 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]
    }
}
5
Blahji

si vous voulez utiliser HEX au lieu de RGBA, faites simplement glisser un nouveau .Swift vide et ajoutez le code mentionné ci-dessous:

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

de même, faites glisser un autre fichier .Swift vide et ajoutez le code mentionné ci-dessous:

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

après cela dans le contrôleur de vue, sous la classe instanciez votre classe 'Couleur' ​​comme ceci:

let colors = Colors()

ajouter une nouvelle fonction: 

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

indiquez cette fonction dans viewDidLoad:

refresh()

vous avez terminé:)) utiliser HEX est bien trop facile si on le compare à RGBA. :RÉ

3
Satnam Sync

Swift 4

Ajouter un point de vue

@IBOutlet weak var gradientView: UIView!

Ajouter un dégradé à la vue

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)
}
3
Vivek Jayakumar

Swift 3 - Utilise uniquement les textures et SKSpriteNode, ne nécessite pas 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!)

    }
}

Usage:

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

Pour que Swift applique CAGradientLayer à n’importe quel objet (horizontal et vertical)

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
}

Comment utiliser

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)

Vous pouvez vérifier la sortie ici

1
Hardik Thakkar

Si vous avez view Collection (Multiple View) faire ceci 

  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
iTALIYA

Code plus propre qui vous permet de passer toute UIColor à une instance de la classe 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]
    }
}
0
Cesare

C'est facile 

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

Utilisez comme ceci: -

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)
0
Rohit Sisodia

Pour ajouter un dégradé au calque, ajoutez:

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)
0
Alexandr Arsenyuk

Je voulais ajouter un dégradé à une vue, puis l'ancrer à l'aide de la disposition automatique.

    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

    }
}
0
r3dm4n

Extension facile à utiliser sur 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)
    }
}

utiliser à votre avis, exemple

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

vous pouvez créer un dégradé avec cette extension

extension UIView {
func setGradient(from color1: UIColor, to color2: UIColor) {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.colors = [color1.cgColor, color2.cgColor]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 1, y: 1)
    gradient.frame = self.layer.frame
    self.layer.insertSublayer(gradient, at: 0)
}

}

0
HardikParmar

Voici une extension Swift où vous pouvez passer n'importe quelle quantité de couleurs arbitraires. Il supprimera tous les dégradés précédents avant d'en insérer un et retournera le calque de dégradé inséré pour une manipulation ultérieure, si nécessaire:

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

Voici une variante pour l’installer dans un fichier de classe Util réutilisable

Dans votre projet Xcode:

  1. Créez une nouvelle classe Swift, appelez-la UI_Util.Swift et remplissez-la comme suit:

    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. Vous pouvez maintenant appeler la fonction depuis n’importe quel ViewController comme ceci:

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

Merci à la réponse de Katwal-Dipak pour le code de fonction

0
Gene Bo

Spécifiez simplement le cadre de la vue où vous souhaitez afficher la couleur du dégradé.

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)
0
Dupinder kaur

Utilisez le code ci-dessous: 

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

appelez cette fonction comme: 

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

Il existe une bibliothèque appelée Chameleon ( https://github.com/viccalexander/Chameleon ) que l’on peut utiliser pour les dégradés de couleurs. Il a même des styles de dégradé à implémenter. Voici comment l’ajouter dans 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
Captain Newt