Search code examples
iosswiftswift3savescale

scale image to smaller size in swift3


I am trying to scale a image that is being graphic programmed into the photo gallery. I am trying to scale the image to make it smaller. How would I use the code below to make the image smaller

   image1.scale

Solution

  • Use this extension to resize your image:

    extension UIImage{
    
    func resizeImageWith(newSize: CGSize) -> UIImage {
    
        let horizontalRatio = newSize.width / size.width
        let verticalRatio = newSize.height / size.height
    
        let ratio = max(horizontalRatio, verticalRatio)
        let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
        UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
        draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
        }
    
    
    }
    

    Basically you are calculating the aspect ratio to keep the image intact while resizing it. Then you are getting the current image context and drawing it in the specified rectangle and finally returning it as a new image.