Swift:如何在Swift / SwiftUI中创建此动画?

时间:2020-08-29 03:44:04

标签: swift swiftui uikit core-animation swiftui-animation

我一直在研究动画,并且想知道如何在UIKit / SwiftUI中创建这样的动画?如果我要进一步研究动画,又叫什么动画?它不必是确切的布局,例如,单行uiview / uiimageview绰绰有余。我只需要知道执行这种动画的方式/方法。

enter image description here

1 个答案:

答案 0 :(得分:0)

使用Swift / UIKit可以通过起诉CAKeyframeAnimation来实现。以下是相同的示例代码。假设存在一个UIImageView,名称为imageView,请根据需要更改图像文件的名称。

func createPanXAnimation() {
    
    let scaleLayer = CALayer()
    scaleLayer.frame = imageView.bounds.insetBy(dx: -200, dy: -200)
    
    scaleLayer.contents = UIImage(named: <#ImageResourceName#>)!.cgImage!
    imageView.layer.addSublayer(scaleLayer)

    let centerX = imageView.bounds.width/2.0
    let xPositionArray: [NSNumber] = [100, 200, 250]

    var timesArray: [NSNumber] = [0, 0.3, 0.6]
    timesArray.append(1.0)

    // Total loop time
    let time : Float = 3

    let animation = CAKeyframeAnimation(keyPath: "position.x")
    animation.beginTime = 0
    animation.duration = CFTimeInterval(time)
    animation.repeatCount = Float.greatestFiniteMagnitude;
    animation.isRemovedOnCompletion = false
    animation.fillMode = CAMediaTimingFillMode.forwards
    animation.autoreverses = true
    animation.values = xPositionArray
    animation.keyTimes = timesArray
    //animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    animation.calculationMode = CAAnimationCalculationMode.linear

    scaleLayer.add(animation, forKey: "position.x")
    
}

希望它能给您一些想法,如果不是复制/粘贴解决方案。 ?