一个轻量级、与SwiftUI兼容的库,用于高效地从网络URL加载、缓存和显示图像。CachedNetworkImage
通过缓存图像来减少冗余的网络请求,并支持可自定义的占位符、错误处理和可选的调整大小,以提高性能。
import SwiftUI
import CachedNetworkImage
struct ContentView: View {
var body: some View {
CachedNetworkImage(
url: URL(string: "https://example.com/image.jpg"),
imageView: { $0.resizable() },
placeholder: { ProgressView() },
errorView: { error in Text("Error: \(error.localizedDescription)") }
)
.scaledToFit()
.frame(width: 200, height: 200)
}
}
参数 | 类型 | 描述 |
---|---|---|
url | URL? | 要加载的图像的 URL |
highRes | Bool | 是否在获取图像后缩小图像尺寸 |
cacheTime | TimeInterval | 缓存图像的生存时间。默认为 1 小时 |
imageView | (Image) -> some View | 当图像传递时使用的 ViewBuilder |
placeholder | () -> some View | 图像正在加载时使用的 ViewBuilder。 默认为 ProgressView |
errorView | (any Error) -> some View | 发生错误时使用的 ViewBuilder |
CachedNetworkImage(
url: URL(string: "https://example.com/image.jpg"),
keepFullRes: false,
cacheTime: 600, // 10 minutes
imageView: { $0.resizable().aspectRatio(contentMode: .fit) },
placeholder: {
VStack {
ProgressView()
Text("Loading image...")
}
},
errorView: { error in
VStack {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.red)
Text("Failed to load image")
}
}
)
本项目采用 MIT 许可证。 有关详细信息,请参阅 LICENSE 文件。
欢迎贡献! 请按照以下步骤操作