another.im-ios/ConversationsClassic/Helpers/UIImage+Crop.swift
2024-08-17 17:41:23 +02:00

31 lines
1.1 KiB
Swift

import Foundation
import UIKit
extension UIImage {
func scaleAndCropImage(_ size: CGSize) async throws -> UIImage {
try await Task {
let aspect = self.size.width / self.size.height
let targetAspect = size.width / size.height
var newWidth: CGFloat
var newHeight: CGFloat
if aspect < targetAspect {
newWidth = size.width
newHeight = size.width / aspect
} else {
newHeight = size.height
newWidth = size.height * aspect
}
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
self.draw(in: CGRect(x: (size.width - newWidth) / 2, y: (size.height - newHeight) / 2, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let newImage = newImage {
return newImage
} else {
throw NSError(domain: "UIImage", code: -900, userInfo: nil)
}
}.value
}
}