【问题标题】:Load Animated gif in UIImageView IOS在 UIImageView IOS 中加载动画 gif
【发布时间】:2016-06-04 14:40:53
【问题描述】:

我的资产文件中有这个 gif

资产的名称是 loading_apple,但是当我添加以下代码时,我得到一个空指针异常错误:

let img = UIImage (named: "loading_apple")

那么我怎样才能显示这个 gif 呢? :(

希望有人可以帮助我。

【问题讨论】:

  • 你确定不是“loading_apple.gif”吗?
  • 是的,我也尝试过使用 loading_apple.gif,其他格式也可以正常使用
  • 尝试使用图像文字:)

标签: ios uiimageview uiimage gif animated


【解决方案1】:

我会推荐使用 FLAnimatedImage https://github.com/Flipboard/FLAnimatedImage

【讨论】:

    【解决方案2】:

    我建议拆分该 gif 的帧并使用 animatedImageNamed:duration: - 您可以将它们命名为所有相似的名称,并在末尾更改数字。例如:

    loading-1.png loading-2.png loading-3.png

    Xcode 会识别出您想要多张图片,并按顺序播放这些图片。

    THIS

    【讨论】:

    • 我尝试过这种方式:let img = UIImage.animatedImageNamed("tmp",duration: 1.0)!,但我得到了同样的错误信息:“unexpectedly found nil while unwrapping an Optional value”
    • 你明白了!很高兴能帮忙
    【解决方案3】:

    你为什么不使用CAReplicatorLayer而不是存储gif文件,参考这个link和这个link in objective c,我在第二个类似的代码中使用了相同的代码并进行了一些修改,

    func spinTheCustomSpinner() -> Void {
        let aBar:CALayer = CALayer.init()
        aBar.bounds = CGRectMake(0, 0, 8, 25);
        aBar.cornerRadius = 4; //(8/2)
        aBar.backgroundColor = UIColor.blackColor().CGColor
        aBar.position = CGPointMake(150.0, 150.0 + 35)
    
        let replicatorLayer:CAReplicatorLayer = CAReplicatorLayer.init()
        replicatorLayer.bounds = CGRectMake(0, 0,300,300)
        replicatorLayer.cornerRadius = 10.0
        replicatorLayer.backgroundColor = UIColor.whiteColor().CGColor
        replicatorLayer.position = CGPointMake(CGRectGetMidX(self.view!.bounds), CGRectGetMidY(self.view!.bounds))
        let angle:CGFloat = CGFloat (2.0 * M_PI) / 12.0
        let transform:CATransform3D = CATransform3DMakeRotation(angle, 0, 0, 1.0)
        replicatorLayer.instanceCount = 12
        replicatorLayer.instanceTransform = transform
        replicatorLayer .addSublayer(aBar)
        self.view!.layer .addSublayer(replicatorLayer)
    
        aBar.opacity = 0.0
        let animationFade:CABasicAnimation = CABasicAnimation(keyPath: "opacity")
        animationFade.fromValue = NSNumber(float: 1.0)
        animationFade.toValue = NSNumber(float: 0.0)
        animationFade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        animationFade.repeatCount = HUGE
        animationFade.duration = 1.0
    
        let aBarAnimationDuration:Double = 1.0/12.0
        replicatorLayer.instanceDelay = aBarAnimationDuration
        aBar .addAnimation(animationFade, forKey: "fadeAnimation")
    
    }
    

    如果你使用上面的视图,在加载时显示这个视图并在加载后隐藏,这真的很酷也很方便,而且不用担心存储 gif 文件和使用图像视图加载。

    通过改变aBar层的属性,你可以获得不同的效果。

    【讨论】:

      【解决方案4】:

      对于这个特定的 gif,您可能需要使用 UIActivityIndicatorView 并使用 startAnimating() 使其动画化

      【讨论】:

        猜你喜欢
        • 2013-05-13
        • 2018-01-26
        • 1970-01-01
        • 2011-05-22
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多