Skip to content

Commit

Permalink
Cache and use previously rendered icons
Browse files Browse the repository at this point in the history
  • Loading branch information
lkeude96 committed Oct 23, 2019
1 parent c230a9e commit fe579f7
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions CardParts/src/Resources/AssetManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,27 @@
import UIKit

class AssetManager {
static var shared = AssetManager()
static let shared = AssetManager()

private var assets: [Icon: UIImage] = [:]
private let cache: NSCache = NSCache<NSString, UIImage>()

init() {
Icon.allCases.forEach { icon in
assets[icon] = render(icon)
}
// render and cache the default size images
Icon.allCases.forEach { icon in _ = image(for: icon)}
}

func image(for icon: Icon) -> UIImage? {
return assets[icon]
func image(for icon: Icon, in rect: CGRect = CGRect(x: 0, y: 0, width: 24.0, height: 24.0)) -> UIImage {
let key = "\(icon)_\(rect.width)x\(rect.height)" as NSString
if let cachedImage = cache.object(forKey: key) {
return cachedImage
}

let image = render(icon, in: rect)
cache.setObject(image, forKey: key)
return image
}

private func render(_ icon: Icon, in rect: CGRect = CGRect(x: 0, y: 0, width: 24.0, height: 24.0)) -> UIImage {
private func render(_ icon: Icon, in rect: CGRect) -> UIImage {
let format = UIGraphicsImageRendererFormat.default()
let renderer = UIGraphicsImageRenderer(size: rect.size, format: format)

Expand Down

0 comments on commit fe579f7

Please sign in to comment.