【问题标题】:How to round UIBezierPath line edge?如何圆 UIBezierPath 线边缘?
【发布时间】:2018-02-13 11:08:02
【问题描述】:

我有一个 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 而变化。

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

P.S.:1.00035 用于消除层之间的间隙。而alpha需要

【问题讨论】:

  • 编辑后,您的问题与原始问题完全不同,这导致所有先前的答案无效。请记住,还(并且主要)添加了答案,以使未来有类似问题的访问者受益。原来的问题已经解决了,那应该是另外一个问题了,考虑单独发一下吧。
  • 费耶,原来的问题已经解决了,但那是一个“拐杖”。在我尝试更改答案代码并添加问题信息之后。问题始终保持不变,因此我认为更改正确答案没有问题,因为我的问题在更改问题信息时并没有解决。

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


【解决方案1】:

通过添加 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

【讨论】:

  • .round 在 Swift 5 上
  • 如果我想要cornerRadius 8怎么办?
【解决方案2】:

执行此操作的一种简单方法是创建向内移动所需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
}

这是示例结果:

【讨论】:

  • 如何使这个元素不透明? (需要使用带有 alpha
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多