This commit is contained in:
fmodf 2024-07-13 18:37:26 +02:00
parent 318d792928
commit 18ea45257b

View file

@ -39,34 +39,23 @@ final class FileProcessing {
}
}
private extension FileProcessing {
func scaleAndCropImage(_ img: UIImage, _ size: CGSize) -> UIImage? {
guard let cgImage = img.cgImage else {
return nil
}
let contextImage: UIImage = .init(cgImage: cgImage)
var contextSize: CGSize = contextImage.size
var posX: CGFloat = 0.0
var posY: CGFloat = 0.0
let cgwidth: CGFloat = size.width
let cgheight: CGFloat = size.height
// Check and handle if the image is wider than the requested size
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
contextSize.width = contextSize.height
} else if contextSize.width < contextSize.height {
// Check and handle if the image is taller than the requested size
posY = ((contextSize.height - contextSize.width) / 2)
contextSize.height = contextSize.width
func scaleAndCropImage(_ img: UIImage, _ size: CGSize) -> UIImage? {
let aspect = img.size.width / img.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
}
let rect: CGRect = .init(x: posX, y: posY, width: cgwidth, height: cgheight)
guard let contextCg = contextImage.cgImage, let imgRef = contextCg.cropping(to: rect) else {
return nil
}
let image: UIImage = .init(cgImage: imgRef, scale: img.scale, orientation: img.imageOrientation)
return image
}
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
img.draw(in: CGRect(x: (size.width - newWidth) / 2, y: (size.height - newHeight) / 2, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}