How to easily resize/optimize an image size with iOS?

后端 未结 18 1506
温柔的废话
温柔的废话 2020-11-22 11:05

My application is downloading a set of image files from the network, and saving them to the local iPhone disk. Some of those images are pretty big in size (widths larger tha

18条回答
  •  清歌不尽
    2020-11-22 11:36

    For Swift 3, the below code scales the image keeping the aspect ratio. You can read more about the ImageContext in Apple's documentation:

    extension UIImage {
        class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
            let scale = newHeight / image.size.height
            let newWidth = image.size.width * scale
            UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
            image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
    }
    

    To use it, call resizeImage() method:

    UIImage.resizeImage(image: yourImageName, newHeight: yourImageNewHeight)
    

提交回复
热议问题