How to animate the frame of an layer with CABasicAnimation?

前端 未结 6 548
刺人心
刺人心 2020-12-05 07:57

I guess I have to convert the CGRect into an object to pass it to fromValue?

This is how I try it, but it doesn\'t work:

CABasicAnimation *frameAnima         


        
6条回答
  •  借酒劲吻你
    2020-12-05 08:22

    Extension in swift 4

    import UIKit
    
    extension CALayer {
        func moveTo(point: CGPoint, animated: Bool) {
            if animated {
                let animation = CABasicAnimation(keyPath: "position")
                animation.fromValue = value(forKey: "position")
                animation.toValue = NSValue(cgPoint: point)
                animation.fillMode = .forwards
                self.position = point
                add(animation, forKey: "position")
            } else {
                self.position = point
            }
        }
    
        func resize(to size: CGSize, animated: Bool) {
            let oldBounds = bounds
            var newBounds = oldBounds
            newBounds.size = size
    
            if animated {
                let animation = CABasicAnimation(keyPath: "bounds")
                animation.fromValue = NSValue(cgRect: oldBounds)
                animation.toValue = NSValue(cgRect: newBounds)
                animation.fillMode = .forwards
                self.bounds = newBounds
                add(animation, forKey: "bounds")
            } else {
                self.bounds = newBounds
            }
        }
    
        func resizeAndMove(frame: CGRect, animated: Bool, duration: TimeInterval = 0) {
            if animated {
                let positionAnimation = CABasicAnimation(keyPath: "position")
                positionAnimation.fromValue = value(forKey: "position")
                positionAnimation.toValue = NSValue(cgPoint: CGPoint(x: frame.midX, y: frame.midY))
    
                let oldBounds = bounds
                var newBounds = oldBounds
                newBounds.size = frame.size
    
                let boundsAnimation = CABasicAnimation(keyPath: "bounds")
                boundsAnimation.fromValue = NSValue(cgRect: oldBounds)
                boundsAnimation.toValue = NSValue(cgRect: newBounds)
    
                let groupAnimation = CAAnimationGroup()
                groupAnimation.animations = [positionAnimation, boundsAnimation]
                groupAnimation.fillMode = .forwards
                groupAnimation.duration = duration
                groupAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
                self.frame = frame
                add(groupAnimation, forKey: "frame")
    
            } else {
                self.frame = frame
            }
        }
    }
    

提交回复
热议问题