Ste*_*Vet 3 memory-management uiimage swiftui
我使用这个简单的代码从 Temp 目录加载图像
struct AddNewMedia: View {
@State var filename:String
func imageFullPath(filename:String)->UIImage {
let pathToTemoDir = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
return UIImage(contentsOfFile: pathToTemoDir.path)!
}
var body: some View {
Image(uiImage: self.imageFullPath(filename: filename))
.resizable()
.scaledToFit()
}
}
Run Code Online (Sandbox Code Playgroud)
每个新图像都需要大量内存才能可视化。在这个项目中,我需要加载 20-30 个图像,因此我应该减少每个图像所需的内存,现在每个图像大约 23mb。
是否可以直接从图像路径加载图像而不将其添加到内存中?有什么建议么?非常感谢!
您想要在应用程序中显示的任何内容都应该加载到内存中,因此我相信这部分无需执行任何操作。
在 iOS 上,UIImage 的内存使用量与图像尺寸相关。例如,如果您有 1920x1080 的图像,它将大约消耗大约 8 兆字节的内存(1920 * 1080 * 4 字节)。
因为正如WWDC 2018中提到的,“内存使用与图像的尺寸有关,而不是文件大小”。
因此,作为解决方案,您可以使用尺寸较低的图像,或者可以在呈现图像之前对图像进行下采样。
这是一个用于对图像进行下采样的示例函数,归功于此链接
func downsample(imageAt imageURL: URL,
to pointSize: CGSize,
scale: CGFloat = UIScreen.main.scale) -> UIImage? {
// Create an CGImageSource that represent an image
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else {
return nil
}
// Calculate the desired dimension
let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
// Perform downsampling
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
return nil
}
// Return the downsampled image as UIImage
return UIImage(cgImage: downsampledImage)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1436 次 |
最近记录: |