如何舍入UIBezierPath线边缘?

时间:2018-02-13 11:08:02

标签: ios swift xcode core-graphics core-animation

我有UIBezierPath的线条抽屉

let line = CAShapeLayer()
line.path = UIBezierPath(arcCenter: center,
                          radius: radius,
                          startAngle: CGFloat(114.0/180.0) * .pi,
                          endAngle: .pi,
                          clockwise: true).cgPath
line.lineWidth = LINE_WIDTH
line.strokeColor = UIColor.red.withAlphaComponent(0.9).cgColor
line.fillColor = UIColor.clear.cgColor

我尝试通过添加一些新的CAShapeLayer()

来转角
let corner = CAShapeLayer()
corner.path = UIBezierPath(arcCenter: coordByCorner(114.0*1.00035),
                           radius: LINE_WIDTH/2,
                           startAngle: CGFloat(114.0/180.0) * .pi,
                           endAngle: CGFloat(114.0/180.0 + 1) * .pi,
                           clockwise: false).cgPath
corner.strokeColor = UIColor.clear.cgColor
corner.fillColor = UIColor.red.withAlphaComponent(0.9).cgColor

line.addSublayer(corner)

但我认为这是一个非常糟糕的变体,当我更改图层的颜色时,颜色会随着timeInterval的不同而变化。

此外,这一切看起来像这样:

enter image description here

P.S。:1.00035用于消除层之间的间隙。并且alpha需要< 1.0(0.1 - 0.9),那么它的不透明度如何?

2 个答案:

答案 0 :(得分:2)

通过添加kCALineCapRound

解决了问题
let line = CAShapeLayer()
line.path = UIBezierPath(arcCenter: center,
                      radius: radius,
                      startAngle: CGFloat(114.0/180.0) * .pi,
                      endAngle: .pi,
                      clockwise: true).cgPath
line.lineWidth = LINE_WIDTH
line.strokeColor = UIColor.red.withAlphaComponent(0.9).cgColor
line.fillColor = UIColor.clear.cgColor
line.lineCap = kCALineCapRound // this parameter solve my problem

答案 1 :(得分:1)

这样做的一个简单方法是创建向前移动所需cornerRadius的路径,用两倍粗线划线,并应用圆线连接样式。

let layer = CAShapeLayer()

layer.strokeColor = UIColor.lightGray.cgColor
layer.fillColor = UIColor.lightGray.cgColor
layer.lineWidth = 2.0 * cornerRadius
layer.lineJoin = kCALineJoinRound
layer.path = getSemicirclePath(
    arcCenter: arcCenter,
    radius: radius,
    cornerRadius: cornerRadius
)

func getSemicirclePath(arcCenter: CGPoint, radius: CGFloat, cornerRadius: CGFloat) -> CGPath {
    let path = UIBezierPath(
        arcCenter: CGPoint(x: arcCenter.x, y: arcCenter.y - cornerRadius),
        radius: radius - cornerRadius,
        startAngle: .pi,
        endAngle: 2.0 * .pi,
        clockwise: true
    )
    path.close()
    return path.cgPath
}

以下是示例结果:

enter image description here