On OSX, how do I gradient fill a path stroke?

前端 未结 3 463
遇见更好的自我
遇见更好的自我 2020-12-04 18:32

Using the plethora of drawing functions in Cocoa or Quartz it\'s rather easy to draw paths, and fill them using a gradient. I can\'t seem to find an acceptable way however,

3条回答
  •  醉酒成梦
    2020-12-04 19:34

    According to Peter Hosey's answer I've managed to do a simple gradient curve, which looks like this:

    I've done this in drawRect(_:) method of UIView class by writing the code below:

    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
    
        CGContextBeginTransparencyLayer (context, nil)
        let path = createCurvePath()
        UIColor.blueColor().setStroke()
        path.stroke()
        CGContextSetBlendMode(context, .SourceIn)
    
        let colors          = [UIColor.blueColor().CGColor, UIColor.redColor().CGColor]
        let colorSpace      = CGColorSpaceCreateDeviceRGB()
        let colorLocations  :[CGFloat] = [0.0, 1.0]
        let gradient        = CGGradientCreateWithColors(colorSpace, colors, colorLocations)
        let startPoint      = CGPoint(x: 0.0, y: rect.size.height / 2)
        let endPoint        = CGPoint(x: rect.size.width, y: rect.size.height / 2)
    
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, CGGradientDrawingOptions.DrawsBeforeStartLocation)
        CGContextEndTransparencyLayer(context)
    }
    

    Function createCurvePath() returns an UIBezierPath object. I've also set path.lineWidth to 5 points.

提交回复
热议问题