如何围绕自己的边界中心旋转UIBezierPath?

时间:2018-04-25 00:59:14

标签: rotation core-graphics uibezierpath cgaffinetransform

让我们说我们有一个UIBezierPath ......其界限完全正方形......就像这样:

func getExponentPath(rotate180: Bool) -> UIBezierPath {

    // establish unit of measure (grid) based on this containing view's bounds... (not to be confused with this bezierpath's bounds)

    let G = bounds.width / 5

    let exponentPath = UIBezierPath()

    let sstartPoint = CGPoint(x:(3.8)*G,y:(1.2)*G)
    exponentPath.move(to: sstartPoint)
    exponentPath.addLine(to: CGPoint(x:(5)*G,y:(1.2)*G))
    exponentPath.addLine(to: CGPoint(x:(4.4)*G,y:(0.2)*G))
    exponentPath.addLine(to: CGPoint(x:(5)*G,y:(0.2)*G))
    exponentPath.addLine(to: CGPoint(x:(5)*G,y:(0)*G))
    exponentPath.addLine(to: CGPoint(x:(3.8)*G,y:(0)*G))
    exponentPath.addLine(to: CGPoint(x:(3.8)*G,y:(0.2)*G))
    exponentPath.addLine(to: CGPoint(x:(4.4)*G,y:(0.2)*G))
    exponentPath.addLine(to: sstartPoint)

    exponentPath.close()

    // this does not work:
    // if rotate180 { exponentPath.apply(CGAffineTransform(rotationAngle: CGFloat.pi)) }

    return exponentPath

}

如果旋转,此bezier路径仍然需要在其包含视图中占据完全相同的区域。

我只能假设这不起作用,因为旋转中心的某些问题不是我想要的...虽然我得到相同(错误)的结果,即使说"旋转0"

那么如何围绕它自己的中心点旋转路径?

似乎应该有一个简单的线性代数矩阵乘法类型,可以应用于这组点。 = T

3 个答案:

答案 0 :(得分:1)

我认为你不需要轮换。要颠倒相同的形状,只需翻转它:

        exponentPath.apply(CGAffineTransform(scaleX: 1, y: -1))
        exponentPath.apply(CGAffineTransform(translationX: 0, y: G))

答案 1 :(得分:1)

所以如果其他人试图在它的中心旋转UIBezierPath的自己的边界矩形......这是在以前的答案/评论的帮助下得到的实际工作解决方案:

func getExponentPath(rotationAngle: CGFloat) -> UIBezierPath {

    // ...

    let x_translation = -( (bounds.width) - ( exponentPath.bounds.width/2) )
    let y_translation = -exponentPath.bounds.height/2

    exponentPath.apply(CGAffineTransform(translationX: x_translation, y: y_translation))
    exponentPath.apply(CGAffineTransform(rotationAngle: rotationAngle))
    exponentPath.apply(CGAffineTransform(translationX: -x_translation, y: -y_translation))

    // ...

}

答案 2 :(得分:1)

extension UIBezierPath
{
    func rotateAroundCenter(angle: CGFloat)
    {
        let center = self.bounds.getCenter()
        var transform = CGAffineTransform.identity
        transform = transform.translatedBy(x: center.x, y: center.y)
        transform = transform.rotated(by: angle)
        transform = transform.translatedBy(x: -center.x, y: -center.y)
        self.apply(transform)
    }
}