Search code examples
swiftuibezierpathcashapelayercabasicanimationcgpath

How do I flip over a UIBezierPath or cgPath thats animated onto the CAShapeLayer?


I have an array of type [UIBezierPath] that I transform into cgPaths and then animate onto a CAShapeLayer I called shapeLayer. Now for some reason all my paths are upside down, so all the paths get drawn upside down. How can I fix this, I tried a couple of methods but sadly none of them worked... I did however figure out how to scale the path. This is my code to draw the swiftPath, which is a path made up of UIBezierPaths found in the Forms class under the function swiftBirdForm(). Drawing the path is working fine, I just can't figure out how to flip it 180 degrees.

    @objc func drawForm() {
    var swiftPath = Forms.swiftBirdForm()
    let shapeLayer = CAShapeLayer()
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.black.cgColor
    shapeLayer.lineWidth = 1
    shapeLayer.frame = CGRect(x: -120, y: 120, width: 350, height: 350)

    var paths: [UIBezierPath] = swiftPath

    guard let path = paths.first else {
        return
    }

    paths.dropFirst()
        .forEach {
            path.append($0)
    }

    shapeLayer.transform = CATransform3DMakeScale(0.6, 0.6, 0)
    shapeLayer.path = path.cgPath

    self.view.layer.addSublayer(shapeLayer)

    let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
    strokeEndAnimation.duration = 1.0
    strokeEndAnimation.fromValue = 0.0
    strokeEndAnimation.toValue = 1.0
    shapeLayer.add(strokeEndAnimation, forKey: nil)
}

Solution

  • Using CATransform3D

    shapeLayer.transform = CATransform3DMakeScale(1, -1, 1)
    

    Transforming path,

    let shapeBounds = shapeLayer.bounds
    let mirror = CGAffineTransform(scaleX: 1,
                                      y: -1)
    let translate = CGAffineTransform(translationX: 0,
                                      y: shapeBounds.size.height)
    let concatenated = mirror.concatenating(translate)
    
    bezierPath.apply(concatenated)
    
    shapeLayer.path = bezierPath.cgPath
    

    Transforming layer,

    let shapeFrame = CGRect(x: -120, y: 120, width: 350, height: 350)
    let mirrorUpsideDown = CGAffineTransform(scaleX: 1,
                                                  y: -1)
    shapeLayer.setAffineTransform(mirrorUpsideDown)
    shapeLayer.frame = shapeFrame