CoreGraphics - 绘制弧形笔划

时间:2015-03-14 19:00:32

标签: ios swift core-graphics

我有一个弧形的UIBezierPath。我只想将笔画绘制到图形上下文(即弧的笔划,不包括连接弧的终点和起点的线)

一旦我完成了这个,我就可以在上下文中添加线性渐变,有效地在弧形笔划上绘制渐变。

这是我的drawRect:

    let context = UIGraphicsGetCurrentContext()

    CGContextSaveGState(context)
    CGContextAddPath(context, _progressPathForProgress(_progressToDrawForProgress(progress)).CGPath)
    CGContextStrokePath(context)
    CGContextClip(context)

    let colours = [self.startColour.CGColor, self.endColour.CGColor]
    let colourSpace = CGColorSpaceCreateDeviceRGB()
    let colourLocations: [CGFloat] = [0.0, 1.0]

    let gradient = CGGradientCreateWithColors(colourSpace, colours, colourLocations)

    var startPoint = CGPoint.zeroPoint
    var endPoint = CGPoint(x: 0, y: bounds.height)
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, CGGradientDrawingOptions.allZeros)

    CGContextRestoreGState(context)

但这一切都是为我的整个UIView添加渐变。我哪里出错?

1 个答案:

答案 0 :(得分:1)

需要关闭路径才能使裁剪工作。

如果您不想看到结束行,可以将描边颜色设置为UIColor.clearColor(),然后关闭路径。

CGContextSaveGState(context)
CGContextAddPath(context, _progressPathForProgress(_progressToDrawForProgress(progress)).CGPath)
CGContextStrokePath(context)

CGContextSetStrokeColorWithColor(context, UIColor.clearColor().CGColor)

// close the path, you will need to add some more points here, otherwise
// the end point is simply connected to the start point
CGPathCloseSubpath(...)

CGContextClip(context)

// draw the gradient

我将通过添加更多点来关闭路径来解释我的意思。以下图片是我的某个应用程序的屏幕截图,它是一个在图表下方具有渐变的高度配置文件。

enter image description here

直接关闭路径会导致这种情况,这意味着渐变不会被绘制到x轴:

enter image description here

要正确关闭路径,我将最后一个坐标(x,y)的点向下添加到x轴(x,0),然后添加到(0,0),最后用第一个点关闭路径,就像这样:

enter image description here

我不想看到结束行,所以我在这里使用UIColor.clearColor()

希望你能得到这个想法。