我已经编写了以下代码来绘制一个带有整数的矩形:
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},关闭< / p>
正如你所看到的,最后两个条目是lineTo和close,这给了我不是预期的结果(一个完整的圆圈),我什么也得不到,因为333.5和333.4999999之间的线太短了。
自从在Objective-C中切换到Swift 3后出现此问题,这不是一个问题。
将结束角度更改为1.9 * Double.pi也可以使用,不知道为什么。但整个圆圈应该有2 * Double.pi。
任何想法或者它是一个Swift 3错误?
答案 0 :(得分: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