wip
This commit is contained in:
parent
318d792928
commit
18ea45257b
|
@ -39,34 +39,23 @@ final class FileProcessing {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private extension FileProcessing {
|
|
||||||
func scaleAndCropImage(_ img: UIImage, _ size: CGSize) -> UIImage? {
|
func scaleAndCropImage(_ img: UIImage, _ size: CGSize) -> UIImage? {
|
||||||
guard let cgImage = img.cgImage else {
|
let aspect = img.size.width / img.size.height
|
||||||
return nil
|
let targetAspect = size.width / size.height
|
||||||
}
|
var newWidth: CGFloat
|
||||||
let contextImage: UIImage = .init(cgImage: cgImage)
|
var newHeight: CGFloat
|
||||||
var contextSize: CGSize = contextImage.size
|
if aspect < targetAspect {
|
||||||
|
newWidth = size.width
|
||||||
var posX: CGFloat = 0.0
|
newHeight = size.width / aspect
|
||||||
var posY: CGFloat = 0.0
|
} else {
|
||||||
let cgwidth: CGFloat = size.width
|
newHeight = size.height
|
||||||
let cgheight: CGFloat = size.height
|
newWidth = size.height * aspect
|
||||||
|
|
||||||
// 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)
|
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
|
||||||
guard let contextCg = contextImage.cgImage, let imgRef = contextCg.cropping(to: rect) else {
|
img.draw(in: CGRect(x: (size.width - newWidth) / 2, y: (size.height - newHeight) / 2, width: newWidth, height: newHeight))
|
||||||
return nil
|
let newImage = UIGraphicsGetImageFromCurrentImageContext()
|
||||||
}
|
UIGraphicsEndImageContext()
|
||||||
let image: UIImage = .init(cgImage: imgRef, scale: img.scale, orientation: img.imageOrientation)
|
|
||||||
return image
|
return newImage
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue