我需要从 URL 中加载一个动态的 Gif 图片并且显示在 UIImageview 上。
当我使用正常的代码时,这张图片没有加载出来。
是否有其他方法可以加载动态的 Gif 图片呢?
我需要从 URL 中加载一个动态的 Gif 图片并且显示在 UIImageview 上。
当我使用正常的代码时,这张图片没有加载出来。
是否有其他方法可以加载动态的 Gif 图片呢?
UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image1.gif"],
[UIImage imageNamed:@"image2.gif"],
[UIImage imageNamed:@"image3.gif"],
[UIImage imageNamed:@"image4.gif"], nil];
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];
您可以加载多个gif图像。
您可以使用以下ImageMagick命令来拆分gif:
convert +adjoin loading.gif out%d.gif
这已经找到了一个被接受的答案,但我最近发现了UIImage+animatedGIF UIImage扩展。它提供了以下类别:
+[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url]
让您可以轻松地:
#import "UIImage+animatedGIF.h"
UIImage* mygif = [UIImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:@"http://en.wikipedia.org/wiki/File:Rotating_earth_(large).gif"]];
神奇般的工作。
以下是使用 Gif 图像的最佳解决方案。 在您的项目中从 Github 添加 SDWebImage。
#import "UIImage+GIF.h"
_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"];
如果您不想使用第三方库,
extension UIImageView {
func setGIFImage(name: String, repeatCount: Int = 0 ) {
DispatchQueue.global().async {
if let gif = UIImage.makeGIFFromCollection(name: name, repeatCount: repeatCount) {
DispatchQueue.main.async {
self.setImage(withGIF: gif)
self.startAnimating()
}
}
}
}
private func setImage(withGIF gif: GIF) {
animationImages = gif.images
animationDuration = gif.durationInSec
animationRepeatCount = gif.repeatCount
}
}
extension UIImage {
class func makeGIFFromCollection(name: String, repeatCount: Int = 0) -> GIF? {
guard let path = Bundle.main.path(forResource: name, ofType: "gif") else {
print("Cannot find a path from the file \"\(name)\"")
return nil
}
let url = URL(fileURLWithPath: path)
let data = try? Data(contentsOf: url)
guard let d = data else {
print("Cannot turn image named \"\(name)\" into data")
return nil
}
return makeGIFFromData(data: d, repeatCount: repeatCount)
}
class func makeGIFFromData(data: Data, repeatCount: Int = 0) -> GIF? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
print("Source for the image does not exist")
return nil
}
let count = CGImageSourceGetCount(source)
var images = [UIImage]()
var duration = 0.0
for i in 0..<count {
if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
let image = UIImage(cgImage: cgImage)
images.append(image)
let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
source: source)
duration += delaySeconds
}
}
return GIF(images: images, durationInSec: duration, repeatCount: repeatCount)
}
class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
var delay = 0.0
// Get dictionaries
let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
return delay
}
let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)
// Get delay time
var delayObject: AnyObject = unsafeBitCast(
CFDictionaryGetValue(gifProperties,
Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
to: AnyObject.self)
if delayObject.doubleValue == 0 {
delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
}
delay = delayObject as? Double ?? 0
return delay
}
}
class GIF: NSObject {
let images: [UIImage]
let durationInSec: TimeInterval
let repeatCount: Int
init(images: [UIImage], durationInSec: TimeInterval, repeatCount: Int = 0) {
self.images = images
self.durationInSec = durationInSec
self.repeatCount = repeatCount
}
}
使用方法:
override func viewDidLoad() {
super.viewDidLoad()
imageView.setGIFImage(name: "gif_file_name")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
imageView.stopAnimating()
}
请确保将gif文件添加到项目中,而不是.xcassets文件夹中。
请查看此链接:
并导入这两个类:UIImage+animatedGIF.h 和 UIImage+animatedGIF.m
使用以下代码:
NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"];
NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url];
希望这能帮到您
这不符合使用UIImageView的要求,但或许对你来说使用UIWebView会更简单。你考虑过使用UIWebView吗?
NSString *gifUrl = @"http://gifs.com";
NSURL *url = [NSURL URLWithString: gifUrl];
[webView loadRequest: [NSURLRequest requestWithURL:url]
如果你想的话,可以将一个HTML文件导入到Xcode项目中,并在字符串中设置根路径,而不是链接到需要互联网的URL。
这里是一个有趣的库:https://github.com/Flipboard/FLAnimatedImage
我测试了演示例子,效果很好。它是UIImageView的子类,所以我认为您也可以直接在StoryBoard中使用它。
祝好!
我知道已经有一个答案被批准了,但是很难不想分享一下我的经验,我创建了一个嵌入式框架,可以为iOS添加Gif支持,感觉就像使用任何其他UIKit框架类一样。
这里有一个例子:
UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData];
anUiImageView.image = gif;
从https://github.com/ObjSal/UIGifImage/releases下载最新版。
-- Sal
SWIFT 3
以下是需要Swift版本的更新!
几天前,我需要做这样一件事情。根据特定的参数从服务器加载一些数据,并在此期间显示不同的“加载”gif图像。我正在寻找使用UIImageView
实现它的选项,但不幸的是,我没有找到不分割.gif图像就能完成的解决方案。因此,我决定使用UIWebView
来实现一个解决方案,并想要分享它:
extension UIView{
func animateWithGIF(name: String){
let htmlString: String = "<!DOCTYPE html><html><head><title></title></head>" +
"<body style=\"background-color: transparent;\">" +
"<img src=\""+name+"\" align=\"middle\" style=\"width:100%;height:100%;\">" +
"</body>" +
"</html>"
let path: NSString = Bundle.main.bundlePath as NSString
let baseURL: URL = URL(fileURLWithPath: path as String) // to load images just specifying its name without full path
let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
let gifView = UIWebView(frame: frame)
gifView.isOpaque = false // The drawing system composites the view normally with other content.
gifView.backgroundColor = UIColor.clear
gifView.loadHTMLString(htmlString, baseURL: baseURL)
var s: [UIView] = self.subviews
for i in 0 ..< s.count {
if s[i].isKind(of: UIWebView.self) { s[i].removeFromSuperview() }
}
self.addSubview(gifView)
}
func animateWithGIF(url: String){
self.animateWithGIF(name: url)
}
}
UIView
创建了一个扩展,它将UIWebView
作为子视图添加,并显示传递其名称的.gif图像。UIViewController
中,我有一个名为“loadingView”的UIView
,它是我的“加载”指示器,每当我想要显示.gif图像时,我会这样做:class ViewController: UIViewController {
@IBOutlet var loadingView: UIView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureLoadingView(name: "loading.gif")
}
override func viewDidLoad() {
super.viewDidLoad()
// .... some code
// show "loading" image
showLoadingView()
}
func showLoadingView(){
loadingView.isHidden = false
}
func hideLoadingView(){
loadingView.isHidden = true
}
func configureLoadingView(name: String){
loadingView.animateWithGIF(name: "name")// change the image
}
}
configureLoadingView()
并调用showLoadingView()
,hideLoadingView()
,一切都正常运作!但是......如果您将图像拆分,则可以使用名为UIImage.animatedImageNamed
的UIImage
静态方法在单行中对其进行动画处理,如下所示:imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)
。从文档中可以看出:此方法通过将一系列数字添加到name参数中提供的基本文件名来加载一系列文件。包含在动画图像中的所有图像应具有相同的大小和比例。或者,您可以使用UIImage.animatedImageWithImages
方法进行操作,如下所示:let images: [UIImage] = [UIImage(named: "imageName1")!,
UIImage(named: "imageName2")!,
...,
UIImage(named: "imageNameN")!]
imageView.image = UIImage.animatedImage(with: images, duration: 1.0)
来自文档:
从现有的一组图像创建并返回一个动画图像。所有包含在动画图像中的图像应该具有相同的大小和比例。
UIWebView
中的图像标签中嵌入gif。