Files
suixinkan_uikit/suixinkan/Features/Home/Services/HomeMenuIconFactory.swift

60 lines
2.1 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// HomeMenuIconFactory.swift
// suixinkan
//
import UIKit
/// / SF Symbol
enum HomeMenuIconFactory {
/// 使
static let canvasSize = CGSize(width: 24, height: 24)
/// 2426pt
static let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: 18, weight: .medium)
private static let imageCache = NSCache<NSString, UIImage>()
/// Assets SF Symbol
static func image(named iconName: String) -> UIImage? {
let cacheKey = iconName as NSString
if let cachedImage = imageCache.object(forKey: cacheKey) {
return cachedImage
}
let image: UIImage?
if let assetImage = UIImage(named: iconName) {
image = renderOnFixedCanvas(assetImage)
} else {
image = UIImage(systemName: iconName, withConfiguration: symbolConfiguration)
}
if let image {
imageCache.setObject(image, forKey: cacheKey)
}
return image
}
private static func renderOnFixedCanvas(_ image: UIImage) -> UIImage {
let sourceSize = image.size
guard sourceSize.width > 0, sourceSize.height > 0 else {
return image
}
let scale = min(canvasSize.width / sourceSize.width, canvasSize.height / sourceSize.height)
let drawSize = CGSize(width: sourceSize.width * scale, height: sourceSize.height * scale)
let drawRect = CGRect(
x: (canvasSize.width - drawSize.width) / 2,
y: (canvasSize.height - drawSize.height) / 2,
width: drawSize.width,
height: drawSize.height
)
let renderer = UIGraphicsImageRenderer(size: canvasSize)
let renderedImage = renderer.image { _ in
image.withRenderingMode(.alwaysOriginal).draw(in: drawRect)
}
return renderedImage.withRenderingMode(.alwaysTemplate)
}
}