CGGradient和路径裁剪:剪辑周围的奇怪边框

时间:2014-10-10 03:02:33

标签: ios swift core-graphics

我试图在书中重现一个例子 iOS编程:Big Nerd Ranch Guide第4版

请注意,我在Swift中重写了本书中的所有Obj-C代码。

作为一项挑战,本书需要使用Core Graphics绘制这种三角形渐变:

enter image description here

但是当我运行我的代码时,我注意到三角形周围有一个浅灰色的边框:

enter image description here

我无法理解为什么......这是我的代码:

    ....
    // draw circles
    UIColor.grayColor().setStroke()
    path.stroke()

    let logoImg = UIImage(named: "logo.png")
    let realSize:CGSize = logoImg.size.halve() // get a /2 CGSize in order to calculate non-retina size

    let gradientLocations:[CGFloat] = [0, 1]
    let gradientColors:[CGFloat] = [0, 1, 0, 1,
                                    1, 1, 0, 1]
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let gradient = CGGradientCreateWithColorComponents(colorSpace, gradientColors, gradientLocations, 2)

    let gradientClipPath = UIBezierPath()
    gradientClipPath.moveToPoint(CGPoint(x: center.x - realSize.width/2, y: center.y + realSize.height/2 + 30))
    gradientClipPath.addLineToPoint(CGPoint(x: center.x + realSize.width/2, y: center.y + realSize.height/2 + 30))
    gradientClipPath.addLineToPoint(CGPoint(x: center.x, y: center.y - realSize.height/2 - 30))
    gradientClipPath.addLineToPoint(CGPoint(x: center.x - realSize.width/2, y: center.y + realSize.height/2 + 30))
    gradientClipPath.fill()

    // draw gradient
    CGContextSaveGState(currContext)
    gradientClipPath.addClip()
    CGContextDrawLinearGradient(currContext, gradient, CGPoint(x: 0, y: center.y - realSize.height/2 - 30), CGPoint(x: 0, y: center.y + realSize.height/2 + 30), 0)
    CGContextRestoreGState(currContext)

    // draw logo with drop shadow
    ....

设置笔划以清除 或其他颜色 无效。边界仍然存在,它仍然是灰色的。

1 个答案:

答案 0 :(得分:0)

在绘制渐变之前,您无需填充渐变路径。删除这一行:

gradientClipPath.fill()