有没有办法将ovinInRect形式的起点从“右”改为“左”? 似乎无论我如何创造它,“起点”总是在“右侧......”
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)
感谢
答案 0 :(得分:3)
从一个以原点为中心的直径为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)
答案 1 :(得分: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))
}
}