ovalInRect 中的起点

Start point in ovalInRect

有没有办法将起点从 ovalInRect 形式 "right" 更改为 "left"? 似乎无论我如何创建它,"starting" 点总是在“右侧...

 let ovalPath = UIBezierPath(ovalInRect: CGRect(x: 515, y: 276.5, width: 280.5, height: 214.5))
        let ovalShapeLayer = CAShapeLayer()
        ovalShapeLayer.fillColor = UIColor.clearColor().CGColor
        ovalShapeLayer.strokeColor = UIColor.lightGrayColor().CGColor
        ovalShapeLayer.lineWidth = 1.5
        ovalShapeLayer.path = ovalPath.CGPath

        self.view.layer.insertSublayer(ovalShapeLayer, atIndex: 1)

谢谢

从一个以原点为中心的直径为 1 的圆开始,具有您想要的起始角度。然后将该圆圈变成一个椭圆形,以刻在您的矩形上。

extension UIBezierPath {

    convenience init(ovalInRect rect: CGRect, startAngle: CGFloat, clockwise: Bool) {
        self.init()
        // Create a circle at the origin with diameter 1.
        addArcWithCenter(.zero, radius: 0.5, startAngle: startAngle, endAngle: startAngle + 2 * CGFloat(M_PI), clockwise: clockwise)
        closePath()

        // Construct a transform that moves the circle to inscribe `rect`.
        var transform = CGAffineTransformIdentity
        // This part moves the center of the circle to the center of `rect`.
        transform = CGAffineTransformTranslate(transform, rect.midX, rect.midY)
        // This part scales the circle to an oval with the same width and height as `rect`.
        transform = CGAffineTransformScale(transform, rect.width, rect.height)

        applyTransform(transform)
    }

}

使用示例:

let oval = UIBezierPath(ovalInRect: CGRectMake(50, 20, 100, 200), startAngle: CGFloat(-M_PI), clockwise: true)
Swift.print(oval.bounds)

输出:

(50.0, 20.0, 100.0, 200.0)

这是 @rob mayoff 对答案的更新,最新 swift 版本:

extension UIBezierPath {
  convenience init(ovalIn rect: CGRect, startAngle: CGFloat, clockwise: Bool) {
      self.init(arcCenter: CGPoint.zero, radius: 0.5, startAngle: startAngle, endAngle: startAngle + 2 * CGFloat(Float.pi), clockwise: clockwise)
      apply(CGAffineTransform(scaleX: rect.width, y: rect.height))
      apply(CGAffineTransform(translationX: rect.midX, y: rect.midY))
  }
}