【问题标题】:How to add corner radius to a UIBezier Path Arc如何将角半径添加到 UIBezierPath 弧
【发布时间】:2016-03-03 00:15:29
【问题描述】:

我正在使用 UIBezierPath 弧便捷方法创建弧。我希望圆弧的末端被四舍五入 - 请参阅附图以了解确切要求! roundedRect 版本中使用的cornerRadius 选项不适用于 arc 方法。有人对如何实现这一目标有想法吗?提前致谢。 (这与之前提出的问题不同,它提供了确切的要求)

 let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
 let radius: CGFloat = max(bounds.width, bounds.height)
 let arcWidth: CGFloat = 10
 let startAngle: CGFloat = 4.6 / 3 * π
 let endAngle: CGFloat = 4.4 / 3 * π

 let path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true)

 path.lineWidth = arcWidth
 // all thats needed to make the ends rounded is
 path.lineCapStyle = .Round
 path.stroke()

【问题讨论】:

  • 我不知道为什么这个问题被否决了,因为它对我来说非常有意义。但你真的应该接受一个答案
  • 嗨 Philipp,我自己添加了答案,请参阅添加到已编辑问题的评论以及我对 EridB 答案的回复。我希望这对你有所帮助。 R

标签: swift uibezierpath


【解决方案1】:

解决方案

真正的诀窍是 lineCap 属性。您可以使用下面的代码。

func drawCircle(view: UIView, startingAngle: CGFloat, endAngle: CGFloat) -> CAShapeLayer {
    let path = UIBezierPath(arcCenter: view.center, radius: CGFloat((view.bounds.size.height/2) - 10), startAngle: startingAngle, endAngle:endAngle, clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath

    shapeLayer.strokeColor = UIColor.blackColor().CGColor
    shapeLayer.lineWidth = 10.0
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.lineCap = kCALineCapRound

    view.layer.addSublayer(shapeLayer)

    return shapeLayer
}

结果

【讨论】:

  • lineCap 使用定义的常量。不要使用"round" 使用kCALineCapRoundkCALineCapButtkCALineCapSquare。请更新您的答案。
  • 我真的很惊讶为什么这个属性是一个字符串,我不知道它有一个定义的常量。非常感谢您指出@Fogmeister
  • 实际上它们只是字符串,但最好使用常量以防万一将来发生变化 :D 加上编译时检查 :D
  • 确实,当时我在指责 Swift 安全打字,但你注意到了,我改变了看法:D
  • 感谢上面的人的详细回答和对 lineCapStyle 的指点。但我真正需要做的只是添加一行代码 path.lineCapStyle = .Round :-)
【解决方案2】:

只需添加一行代码: path.lineCapStyle = .Round.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多