我已经编写了以下代码来绘制一个带有整体的矩形:

fileprivate let strokeWidth: CGFloat = 5

let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.lineWidth = strokeWidth
shapeLayer.fillColor = UIColor(white: 0.5, alpha: 0.9).cgColor

let p = UIBezierPath(rect: bounds.insetBy(dx: -strokeWidth, dy: -strokeWidth))
let radius = bounds.size.width / 3
p.move(to: CGPoint(x: bounds.midX + radius, y: bounds.midY))
p.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false)
p.close()
shapeLayer.path = p.cgPath

layer.addSublayer(shapeLayer)

这里的问题是这一行:
p.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false)

打印出路径说明:
UIBezierPath:0x6000000b35c0; MoveTo {-5,-5},LineTo {380,-5},LineTo {380,672},LineTo {-5,672},关闭,MoveTo {312.5,333.5},LineTo {312.5,333.49999999999994},Close

如您所见,最后两个条目是lineTo和close,这给我的不是预期的结果(一个完整的圆圈),我什么也不会得到,因为该行在333.5和333.4999999之间太短了。

自从切换到Swift 3(在Objective-C中)以来,就不会出现此问题。

将结束角度更改为1.9 * Double.pi也可以使用,不知道为什么。但是整个圆圈应该有2 * Double.pi。

任何想法还是Swift 3的错误?

最佳答案

尝试这样:

let bounds = UIScreen.main.bounds
let strokeWidth: CGFloat = 5
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.lineWidth = strokeWidth
shapeLayer.fillColor = UIColor(white: 0.5, alpha: 0.9).cgColor
let p = UIBezierPath(rect: bounds.insetBy(dx: -strokeWidth, dy: -strokeWidth))
let radius = bounds.size.width / 3
p.move(to: CGPoint(x: bounds.midX + radius, y: bounds.midY))
p.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 2 * .pi, endAngle: 0, clockwise: false)
p.close()
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 5
shapeLayer.path = p.cgPath
let view = UIView(frame: bounds)
view.backgroundColor = .yellow
view.layer.addSublayer(shapeLayer)

view

ios - Swift 3.0以相同的起点和终点角度绘制圆线-LMLPHP

10-08 07:48