diff --git a/ImageViewer/ViewController.swift b/ImageViewer/ViewController.swift index a39bfcf..9057eae 100644 --- a/ImageViewer/ViewController.swift +++ b/ImageViewer/ViewController.swift @@ -1250,7 +1250,8 @@ class ImageLoader { private var loadingTasks: [String: [((UIImage?) -> Void)]] = [:] init() { - cache.totalCostLimit = 50 * 1024 * 1024 + // 128 MiB + cache.totalCostLimit = 128 * 1024 * 1024 } func preloadImage(at path: URL) { @@ -1277,13 +1278,13 @@ class ImageLoader { let image = UIImage(contentsOfFile: path.path) - DispatchQueue.main.async { - if let image = image, let data = image.pngData() { - self.cache.setObject(image, forKey: path.path as NSString, cost: data.count) - } else { - print("no image to cache found") - } + if let image = image, let cost = imageByteSize(image) { + self.cache.setObject(image, forKey: path.path as NSString, cost: cost) + } else { + print("no image to cache found") + } + DispatchQueue.main.async { self.loadingTasks[path.path]?.forEach { $0(image) } self.loadingTasks.removeValue(forKey: path.path) } @@ -1294,3 +1295,8 @@ class ImageLoader { return cache.object(forKey: path as NSString) } } + +func imageByteSize(_ image: UIImage) -> Int? { + guard let cgImage = image.cgImage else { return nil } + return cgImage.bytesPerRow * cgImage.height +}