For anyone looking for a macOS (App Kit) solution.
NSImage extension
import Foundation
import AppKit
extension NSImage {
func scalePreservingAspectRatio(targetSize: NSSize) -> NSImage {
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
let scaleFactor = min(widthRatio, heightRatio)
let scaledImageSize = NSSize(
width: size.width * scaleFactor,
height: size.height * scaleFactor
)
let newImage = NSImage(size: scaledImageSize)
newImage.lockFocus()
self.draw(in: NSRect(origin: .zero, size: scaledImageSize), from: NSRect(origin: .zero, size: self.size), operation: .copy, fraction: 1.0)
newImage.unlockFocus()
return newImage
}
}
ResizedImage View
import SwiftUI
/// Image resized to a specific size
struct ResizedImage: View {
let resourceName: String
let width: Int
let height: Int
init(_ resourceName: String, width: Int, height: Int) {
self.resourceName = resourceName
self.width = width
self.height = height
}
var body: some View {
if let image = NSImage(named: resourceName) {
let imageResized = image.scalePreservingAspectRatio(targetSize: NSSize(width: 20, height: 20))
Image(nsImage: imageResized)
} else {
// Default questionmark if image is not found
Image(systemName: "questionmark.square")
}
}
}