How to draw a gradient line (fading in/out) with Core Graphics/iPhone?

后端 未结 6 581
轻奢々
轻奢々 2020-12-04 15:02

I know how to draw a simple line:

CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(conte         


        
6条回答
  •  一个人的身影
    2020-12-04 15:15

    I created a Swift version of Benjohn's answer.

    class MyView: UIView {
        override func draw(_ rect: CGRect) {
        super.draw(rect)
    
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
    
        context.addPath(createPath().cgPath)
        context.setLineWidth(15)
        context.replacePathWithStrokedPath()
        context.clip()
    
        let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor] as CFArray, locations: [0, 0.4, 1.0])!
        let radius:CGFloat = 200
        let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
        context.drawRadialGradient(gradient, startCenter: center, startRadius: 10, endCenter: center, endRadius: radius, options: .drawsBeforeStartLocation)
        }
    }
    

    If the createPath() method creates a triangle, you get something like this:

    Hope this helps anyone!

提交回复
热议问题