text Swift - 设置UIView的渐变颜色

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text Swift - 设置UIView的渐变颜色相关的知识,希望对你有一定的参考价值。

See: https://marcosantadev.com/calayer-auto-layout-swift/
Works when you change orientation


import UIKit

class WelcomeViewController: UIViewController {

    var gradientLayer: CAGradientLayer!
    
    @IBOutlet weak var bkView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
  
        gradientLayer = setGradient()
        bkView.layer.addSublayer(gradientLayer)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        gradientLayer.frame = view.bounds
    }
    
}

extension WelcomeViewController {
    
    func setGradient() -> CAGradientLayer {
//        let screenSize = UIScreen.main.bounds
//        let screenWidth = screenSize.width
//        let screenHeight = screenSize.height
        
        let colorTop = UIColor(hex: "e16f00") // Light orange
        let colorBtm = UIColor(hex: "e15700") // Dark orange
        
        let layer = CAGradientLayer()
        //layer.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight )
        layer.colors = [colorTop.cgColor, colorBtm.cgColor] // [UIColor.red.cgColor, UIColor.black.cgColor]
        //bkView.layer.addSublayer(layer)
        return layer
    }
}

// MARK: Extension to UIColor that converts six digit hex color (excludes hash sign and alpha value) into rgb value
extension UIColor {
    convenience init(hex: String) {
        let scanner = Scanner(string: hex)
        scanner.scanLocation = 0
        
        var rgbValue: UInt64 = 0
        
        scanner.scanHexInt64(&rgbValue)
        
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        
        self.init(
            red: CGFloat(r) / 0xff,
            green: CGFloat(g) / 0xff,
            blue: CGFloat(b) / 0xff, alpha: 1
        )
    }
}

以上是关于text Swift - 设置UIView的渐变颜色的主要内容,如果未能解决你的问题,请参考以下文章

swift UIView的渐变视图 - Swift 4.1

如何在 Swift 4 的 UIView 中创建带圆角的渐变边框

Swift:沿贝塞尔路径渐变(使用 CALayers)

如何在 Swift 2.0 中获得正确的 UIView 大小或边界?

iOS - UIView操作(SWift)

如何在 UIView 上设置渐变边框?