Swift 常用框架Kingfisher、KingfisherWebP详解

20 阅读1分钟

1.1 什么是 Kingfisher 、KingfisherWebP

Kingfisher 是一个功能强大的 Swift 库,专门用于处理图像的下载、缓存和展示。目前已成为 iOS/macOS 开发中最受欢迎的图像处理解决方案之一。

KingfisherWebP 是 Kingfisher 的官方扩展,用于支持 WebP 图像格式。WebP 是 Google 开发的一种现代图像格式,它可以在相同质量下提供比 JPEG 和 PNG 更小的文件大小,从而减少带宽使用和加快加载速度。

1.2 核心特性

  • 异步下载 :在后台线程下载图片,不阻塞主线程
  • 多级缓存 :内存缓存 + 磁盘缓存,提高加载速度
  • 自动缓存管理 :智能处理缓存大小和过期时间
  • 图片处理 :支持下载后处理,如圆角、模糊等
  • 请求优先级 :可设置不同图片请求的优先级
  • 可扩展性 :支持自定义缓存、下载器等组件
  • SwiftUI 支持 :提供了便捷的 SwiftUI 视图扩展
  • 动画支持 :支持 GIF 等动画图片

1.3 安装方式

Kingfisher 支持多种安装方式:

CocoaPods:

pod 'Kingfisher'
pod 'KingfisherWebP'

2. Kingfisher 基础用法

2.1 基本图片加载

import Kingfisher

// 基本用法
imageView.kf.setImage(with: URL(string: "https://example.com/image.jpg"))

// 带选项的用法
imageView.kf.setImage(
    with: URL(string: "https://example.com/image.jpg"),
    placeholder: UIImage(named: "placeholder"),
    options: [
        .transition(.fade(0.2)),
        .cacheOriginalImage
    ]
) { result in
    switch result {
    case .success(let value):
        print("Image loaded: \(value.image)")
        print("图片加载成功: \(value.source.url?.absoluteString ?? "")")
    case .failure(let error):
        print("图片加载失败: \(error.localizedDescription)")
    }
}

2.2 缓存控制

 // 清除内存缓存
KingfisherManager.shared.cache.clearMemoryCache()

// 清除磁盘缓存
KingfisherManager.shared.cache.clearDiskCache()

// 清除所有缓存
KingfisherManager.shared.cache.clearCache()

2.3 预加载图像

预加载一组图像以提升加载速度,适合在应用启动时或预期需要时使用。

 let urls = [URL(string: "https://example.com/image1.png")!, URL(string: "https://example.com/image2.png")!]
 ImagePrefetcher(urls: urls).start()

2.4 显示WebP

 /// 全局配置
KingfisherManager.shared.defaultOptions += [.processor(WebPProcessor.default),.cacheSerializer(WebPSerializer.default)]

// 使用 AnimatedImageView 定义ImageView

 let animageView = AnimatedImageView()
 animageView.kf.setImage(with: URL(string: "https://example.com/image.webp"))