iOS设置view渐变

iOS设置view渐变_第1张图片
image.png
func setGradient(colors: [CGColor], startPoint: CGPoint ,endPoint: CGPoint) -> CAGradientLayer {
        let gradientLayer: CAGradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        return gradientLayer
    }

使用:

        let startColor = UIColor.init(red: 228/255.0, green: 203/255.0, blue: 170/255.0, alpha: 1)
        let endColor = UIColor.init(red: 203/255.0, green: 155/255.0, blue: 91/255.0, alpha: 1)
        let gradientColors: [CGColor] = [startColor.cgColor, endColor.cgColor]
        let startPoint = CGPoint(x: 0, y: 0)
        let endPoint = CGPoint(x: 0, y: 1)
        let gradientLayer = header.setGradient(colors: gradientColors, startPoint: startPoint, endPoint: endPoint)
        gradientLayer.frame = header.bounds
        header.layer.insertSublayer(gradientLayer, at: 0)

因为我的视图渐变都是一样的效果,最后改造,一句代码调用解决:

func setRedGradient() {
        let startColor = UIColor.init(red: 228/255.0, green: 203/255.0, blue: 170/255.0, alpha: 1)
        let endColor = UIColor.init(red: 203/255.0, green: 155/255.0, blue: 91/255.0, alpha: 1)
        let gradientColors: [CGColor] = [startColor.cgColor, endColor.cgColor]
        let startPoint = CGPoint(x: 0, y: 0)
        let endPoint = CGPoint(x: 0, y: 1)
        let gradientLayer = self.setGradient(colors: gradientColors, startPoint: startPoint, endPoint: endPoint)
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)

        let gradientLayer: CAGradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
    }

注意:

startPoint与endPoint分别为渐变的起始方向与结束方向,它是以矩形的四个角为基础的,
(0,0)为左上角、
(1,0)为右上角、
(0,1)为左下角、
(1,1)为右下角,
默认是值是(0.5,0)和(0.5,1)

你可能感兴趣的:(iOS设置view渐变)