I am receiving an image from backend that is of a large size as i have to place the same image as profile picture and show the same image on bottom bar in tab bar of size 30x30. I tried to scale down image in various ways but nothing is working.
Tried Alamofire's method which also didn't worked(the image appears to be blurred and distorted):
func resizeImageWithoutDistortion(image: UIImage, size : CGSize) -> UIImage{
// 1. Scale image to size disregarding aspect ratio
let scaledImage = image.af_imageScaled(to: size)
// 2. Scale image to fit within specified size while maintaining aspect ratio
let aspectScaledToFitImage = image.af_imageAspectScaled(toFit: size)
// 3. Scale image to fill specified size while maintaining aspect ratio
let aspectScaledToFillImage = image.af_imageAspectScaled(toFill: size)
return scaledImage.roundImage()
}
Also tried as follows which also didn't worked:
func resizeImage(_ newWidth: CGFloat) -> UIImage {
let ratio = size.width / size.height
if ratio > 1 {
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newWidth))
draw(in: CGRect(x: newWidth * ratio / 2 - newWidth, y: 0, width: newWidth * ratio, height: newWidth))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.roundImage()
} else {
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newWidth))
draw(in: CGRect(x: 0, y: (newWidth / ratio - newWidth) / 2 * (-1), width: newWidth, height: newWidth / ratio))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.roundImage()
}
}