diff --git a/ConversationsClassic/AppCore/Files/FileProcessing.swift b/ConversationsClassic/AppCore/Files/FileProcessing.swift index 9e2de3e..a8fc1c2 100644 --- a/ConversationsClassic/AppCore/Files/FileProcessing.swift +++ b/ConversationsClassic/AppCore/Files/FileProcessing.swift @@ -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 - } - - 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 +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 } + + 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 }