设置椭圆的渐变颜色

时间:2019-04-08 16:34:16

标签: swift uiview uikit core-graphics

我需要为椭圆设置渐变颜色。但是我不知道该怎么做。如何用渐变颜色而不是CGColor填充椭圆。我的代码:

class testView:UIView { 
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        var gradient:CAGradientLayer = CAGradientLayer()
        gradient.frame               = self.bounds
        gradient.colors              = [UIColor.red.cgColor, UIColor.green.cgColor]
        context.addEllipse(in: rect)
        context.setFillColor(UIColor.blue.cgColor)
        context.fillPath()
    }
}

1 个答案:

答案 0 :(得分:0)

快捷键4

这是我当前项目中的复制粘贴。您可以根据自己的目的对其进行修改

var gradientLayer: CAGradientLayer!

func createGradientLayer() {

    var colorIndex: Int = 0

    gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.bounds
    gradientLayer.colors = [myColors[colorIndex][0].cgColor, myColors[colorIndex][1].cgColor]
    gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)

    self.layer.addSublayer(gradientLayer)
}


let myColors: [[UIColor]] = [
    [UIColor.rgb(red: 251, green: 96, blue: 80), UIColor.rgb(red: 192, green: 57, blue: 43)],
    [UIColor.rgb(red: 240, green: 136, blue: 44), UIColor.rgb(red: 211, green: 84, blue: 0)]
]