iOS animate/morph shape from circle to square

后端 未结 4 979
不思量自难忘°
不思量自难忘° 2020-12-03 03:38

I try to change a circle into a square and vice versa and I am almost there. However it doesn\'t animates as expected. I would like all corners of a square to be animated/mo

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 04:15

    After playing with it for a little while in the playground I noticed that each arc adds two segments to the bezier path, not just one. Moreover, calling closePath adds two more. So to keep the number of segments consistent, I ended up with adding fake segments to my square path. The code is in Swift, but I think it doesn't matter.

    func circlePathWithCenter(center: CGPoint, radius: CGFloat) -> UIBezierPath {
        let circlePath = UIBezierPath()
        circlePath.addArcWithCenter(center, radius: radius, startAngle: -CGFloat(M_PI), endAngle: -CGFloat(M_PI/2), clockwise: true)
        circlePath.addArcWithCenter(center, radius: radius, startAngle: -CGFloat(M_PI/2), endAngle: 0, clockwise: true)
        circlePath.addArcWithCenter(center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI/2), clockwise: true)
        circlePath.addArcWithCenter(center, radius: radius, startAngle: CGFloat(M_PI/2), endAngle: CGFloat(M_PI), clockwise: true)
        circlePath.closePath()
        return circlePath
    }
    
    func squarePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
        let squarePath = UIBezierPath()
        let startX = center.x - side / 2
        let startY = center.y - side / 2
        squarePath.moveToPoint(CGPoint(x: startX, y: startY))
        squarePath.addLineToPoint(squarePath.currentPoint)
        squarePath.addLineToPoint(CGPoint(x: startX + side, y: startY))
        squarePath.addLineToPoint(squarePath.currentPoint)
        squarePath.addLineToPoint(CGPoint(x: startX + side, y: startY + side))
        squarePath.addLineToPoint(squarePath.currentPoint)
        squarePath.addLineToPoint(CGPoint(x: startX, y: startY + side))
        squarePath.addLineToPoint(squarePath.currentPoint)
        squarePath.closePath()
        return squarePath
    }
    

    enter image description here

提交回复
热议问题