Kingfisher
Kingfisher
是一个功能强大的纯 Swift
库,用于从Web
下载和缓存图像。它使您有机会在下一个应用程序中使用纯 Swift
方式处理远程图像。
特征
- 异步图像下载和缓存。
- 从URLSession基于网络或本地提供的数据加载图像。
- 提供有用的图像处理器和过滤器。
- 内存和磁盘的多层混合缓存。
- 对缓存行为的精细控制。可定制的到期日期和大小限制。
- 可取消下载和自动重用以前下载的内容以提高性能。
- 独立组件。根据需要分别使用下载器、缓存系统和图像处理器。
- 预取图像并从缓存中显示它们以提升您的应用程序。
-
UIImageView
,NSImageView
,NSButton
,UIButton
,NSTextAttachment
,和的扩展名-WKInterfaceImage
,用于直接从 URL 设置图像。TVMonogramViewCPListItem
- 设置图像时内置过渡动画。
- 加载图像时可自定义的占位符和指示器。
- 易于扩展的图像处理和图像格式。
- 低数据模式支持。
-
SwiftUI
支持。
使用方法
最简单的用例是将图像设置为带有UIImageView
扩展名的图像视图:
import Kingfisher
let url = URL(string: "https://example.com/image.png")
imageView.kf.setimage(with: url)
Kingfisher
将从 下载图像url
,将其发送到内存缓存和磁盘缓存,并以imageView
. 当您稍后使用相同的 URL
设置它时,图像将从缓存中检索并立即显示。
如果您使用 SwiftUI,它也可以工作:
var body: some View {
KFImage(URL(string: "https://example.com/image.png")!)
}
高级的例子
借助强大的选项,您可以用 Kingfisher 以简单的方式完成艰巨的任务。例如,下面的代码:
-
下载高分辨率图像。
-
对其进行下采样以匹配图像视图大小。
-
使其以给定的半径转角。
-
下载时显示系统指示器和占位符图像。
-
原始的大图像也被缓存到磁盘以供以后使用,以避免在详细视图中再次下载它。
-
任务完成时会打印控制台日志,无论是成功还是失败。
let url = URL(string: “https://example.com/high_resolution_image.png”)
let processor = DownsamplingImageProcessor(size: imageView.bounds.size)
|> RoundCornerImageProcessor(cornerRadius: 20)
imageView.kf.indicatorType = .activity
imageView.kf.setimage(
with: url,
placeholder: UIImage(named: “placeholderImage”),
options: [
.processor(processor),
.scaleFactor(UIScreen.main.scale),
.transition(.fade(1)),
.cacheOriginalImage
])
{
result in
switch result {
case .success(let value):
print(“Task done for: (value.source.url?.absoluteString ?? “”)”)
case .failure(let error):
print(“Job Failed: (error.localizedDescription)”)
}
}
这是我在日常工作中经常遇到的情况。想想没有Kingfisher
你需要写多少行!
方法链
如果您不是kf扩展的粉丝,您也可以更喜欢使用KF构建器并链接方法调用。下面的代码做同样的事情:
// Use `kf` extension
imageView.kf.setimage(
with: url,
placeholder: placeholderImage,
options: [
.processor(processor),
.loaddiskFileSynchronously,
.cacheOriginalImage,
.transition(.fade(0.25)),
.lowDataMode(.network(lowResolutionURL))
],
progressBlock: { receivedSize, totalSize in
// Progress updated
},
completionHandler: { result in
// Done
}
)
// Use `KF` builder
KF.url(url)
.placeholder(placeholderImage)
.setProcessor(processor)
.loaddiskFileSynchronously()
.cacheMemoryOnly()
.fade(duration: 0.25)
.lowDataModeSource(.network(lowResolutionURL))
.onProgress { receivedSize, totalSize in }
.onSuccess { result in }
.onFailure { error in }
.set(to: imageView)
更好的是,如果以后你想切换到 SwiftUI,只需将KF上面的内容更改为KFImage,你就完成了:
struct ContentView: View {
var body: some View {
KFImage.url(url)
.placeholder(placeholderImage)
.setProcessor(processor)
.loaddiskFileSynchronously()
.cacheMemoryOnly()
.fade(duration: 0.25)
.lowDataModeSource(.network(lowResolutionURL))
.onProgress { receivedSize, totalSize in }
.onSuccess { result in }
.onFailure { error in }
}
}