Kingfisher 是一个功能强大的纯 Swift 库,用于从Web下载和缓存图像。它使您有机会在下一个应用程序中使用纯 Swift 方式处理远程图像。

UIImageView, NSImageView, NSButton, UIButton, NSTextAttachment,和的扩展名- WKInterfaceImage,用于直接从 URL 设置图像。TVMonogramViewCPListItemSwiftUI 支持。最简单的用例是将图像设置为带有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 }
}
}