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
}
}
当我想更改 gif 图像时,只需使用我的新 .gif 图像的名称调用函数 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)
来自文档:
从现有图像集创建并返回动画图像。动画图像中包含的所有图像都应具有相同的大小和比例。