fmodf
b3b3b3aef7
Reviewed-on: narayana/conversations-classic-ios#1 Co-authored-by: fmodf <fmodf.ios@gmail.com> Co-committed-by: fmodf <fmodf.ios@gmail.com>
31 lines
1.1 KiB
Swift
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
|
|
}
|
|
}
|