【问题标题】:How to show gif into UIImageView in Swift?如何在 Swift 中将 gif 显示到 UIImageView 中?
【发布时间】:2014-08-20 12:57:59
【问题描述】:

我想在 UIImageView 中使用 gif,但我不能。 我的代码是:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"gif"];
    UIImage *testImage = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]];
    self.dataImageView.animationImages = testImage.images;
    self.dataImageView.animationDuration = testImage.duration;
    self.dataImageView.animationRepeatCount = 1;
    self.dataImageView.image = testImage.images.lastObject;
    [self.dataImageView startAnimating];
}

斯威夫特:

var url : NSURL = NSBundle.mainBundle().URLForResource("MAES", withExtension: "gif")

在目标 C 中我有 animatedImageWithAnimatedGIFData 但在swift中我不知道如何调用它或者如果不存在..

谢谢!

【问题讨论】:

标签: animation swift gif ios8


【解决方案1】:

我假设您使用 https://github.com/mayoff/uiimage-from-animated-gif 代替 +UIImage animatedImageWithAnimatedGIFData: 并且源代码在 Objective-C 中。

您需要先将 Objective-C 标头导入 Swift。 Using Swift with Cocoa and Objective-C 解释了如何做到这一点:

要在与您的 Swift 代码相同的框架目标中导入一组 Objective-C 文件, 你需要将这些文件导入到 Objective-C 的伞头文件中 框架。

将 Objective-C 代码从同一框架导入 Swift

  1. 在 Build Settings 下的 Packaging 中,确保该框架目标的 Defines Module 设置设置为 Yes。
  2. 在您的总括头文件中,导入您想要向 Swift 公开的每个 Objective-C 头文件。例如:

    #import "UIImage+animatedGIF.h"

然后您可以按如下方式设置您的testImage

var testImage = UIImage.animatedImageWithAnimatedGIFData(
    NSData.dataWithContentsOfURL(url))
self.dataImageView.animationImages = testImage.images
self.dataImageView.animationDuration = testImage.duration
self.dataImageView.animationRepeatCount = 1
self.dataImageView.image = testImage.images.lastObject
self.dataImageView.startAnimating()

【讨论】:

  • 太棒了!谢谢!没关系。但是我还有一个问题,没有IImage+animatedGIF还有其他形式直接显示gif吗?
  • UIImage 不支持 animated GIF,但您可以像使用任何其他图像一样使用静止的 GIF 图像 (UIImage(named: "image.gif"))。但是,如果您可以将动画 GIF 拆分为单独的静止图像 GIF,则可以将它们加载到 UIImage 动画中,如下所示:stackoverflow.com/a/2578648/2155985
猜你喜欢
  • 2015-04-15
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
  • 2018-01-26
  • 2018-09-21
  • 2015-10-22
  • 2019-09-17
  • 1970-01-01
相关资源
最近更新 更多