如何使用UIGraphicsGetCurrentContext应用渐变颜色

时间:2018-03-15 13:07:31

标签: ios iphone colors swift4 gradient

我使用以下代码绘制三角形

class TriangleView : UIView {

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

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

    override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }

        context.beginPath()
        context.move(to: CGPoint(x: (rect.maxX / 2.0), y: rect.maxY))
        context.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        context.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
        context.closePath()

        context.setFillColor(red: 0.0, green: 0.7, blue: 0.0, alpha: 1)
        context.fillPath()
    }
}

第二行是用绿色填充颜色。 我想用渐变替换这种绿色。

我试过的代码是吼叫

let triangle = TriangleView(frame: CGRect(x: triangleX, y: triangleY, width: triangleWidth , height: triangleHeight))

        // MAKING GRADIENT COLOR
        gradientLayer = CAGradientLayer()
        gradientLayer.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]

        triangle.layer.addSublayer(gradientLayer)
        triangle.backgroundColor = UIColor.clear

它没有效果,颜色仍然是绿色

1 个答案:

答案 0 :(得分:0)

使用CGContext向路径添加渐变有点困难。如果您有兴趣,可以使用此解决方案: How to fill a path with gradient in drawRect:?

但是,我更喜欢使用CAShapeLayer并屏蔽我的CAGradientLayer。 我发现它更简单,代码更少。

class View: UIView {

    var gradientLayer = CAGradientLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        let gradientMask = CAShapeLayer()
        let path = CGMutablePath()
        path.move(to: CGPoint(x: (bounds.maxX / 2.0), y: bounds.maxY))
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
        path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY))
        path.closeSubpath()
        gradientMask.path = path

        gradientLayer.colors = [UIColor.red, UIColor.yellow].map{$0.cgColor}
        gradientLayer.mask = gradientMask
        layer.insertSublayer(gradientLayer, at: 0)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

我用了游乐场,得到了这样的东西:

Triangle Gradient