Resize UIImage to 200x200pt/px

前端 未结 13 2108
后悔当初
后悔当初 2020-11-27 11:25

I have been struggling resizing an image. Basically I have stumpled upon: How to scale down a UIImage and make it crispy / sharp at the same time instead of blurry?

13条回答
  •  無奈伤痛
    2020-11-27 11:50

    This is a continuation to @Christoph R 's answer posted for Swift 3.0. This code works for Swift 5.0.1.

    static func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
    
        let scale = newWidth / image.size.width
        let newHeight = image.size.height * 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!
    }
    

    at callers site

    TaskUtilties.resizeImage(image: rawImage!, newWidth: CGFloat(50))
    

提交回复
热议问题