如何将 UIBezierPath 线边倒圆角?

问题描述 投票:0回答:3

我有一条由

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)

但我认为这是一个不好的变体,当我改变图层的颜色时,颜色会随着时间间隔的不同而变化。

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

P.S.: 1.00035 是为了消除层与层之间的间隙。阿尔法需要是< 1.0 (0.1 - 0.9). So how to do this while keeping the alpha?

ios swift core-graphics core-animation
3个回答
13
投票

问题通过添加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
投票

这样做的一个简单方法是创建向内移动所需

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
}

这里是示例结果:


0
投票

根据当前版本的另一种方式

line.path.lineCapStyle = .round

.path 是 UIBezierPath

参考:https://developer.apple.com/documentation/uikit/uibezierpath/1624347-linecapstyle

© www.soinside.com 2019 - 2024. All rights reserved.