【问题标题】:Start point in ovalInRect椭圆形矩形中的起点
【发布时间】:2016-07-03 22:50:08
【问题描述】:

有没有办法将起点从“右”的椭圆形矩形更改为“左”? 似乎无论我如何创建它,“起点”总是在“右侧......

 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)

谢谢

【问题讨论】:

  • 如果你使用bezierPathWithArcCenter:radius:startAngle:endAngle:clockwise:,你可以控制开始和结束,所以如果你从-M_PI转到M_PI,它将从左边开始。但这无疑是一个圈子。如果你需要椭圆,从左边开始,那么你要么需要定义你自己的UIBezierPath,要么使用这个例程,但是转换视图/图层以便翻转它。
  • 我已经尝试过了,但它什么也没做... let mirrorXorigin = CGAffineTransformMakeScale(-1.0, 1.0) olivePath.applyTransform(mirrorXorigin)
  • shapeLayer 没有 applyTransform
  • 对不起。这会引发错误...

标签: ios swift2 uibezierpath


【解决方案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)

【讨论】:

    【解决方案2】:

    这是 @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))
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2020-04-14
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多