Resize UIImage to 200x200pt/px

前端 未结 13 2143
后悔当初
后悔当初 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条回答
  •  猫巷女王i
    2020-11-27 12:01

    Swift 4.0 -

    If you're dealing with images that contain transparencies, then the accepted answer function will actually convert the transparent areas to black.

    If you wish to scale and keep the transparencies in place, try this function:

    func resizeImageWith(image: UIImage, newSize: CGSize) -> UIImage {
    
        let horizontalRatio = newSize.width / image.size.width
        let verticalRatio = newSize.height / image.size.height
    
        let ratio = max(horizontalRatio, verticalRatio)
        let newSize = CGSize(width: image.size.width * ratio, height: image.size.height * ratio)
        var newImage: UIImage
    
        if #available(iOS 10.0, *) {
            let renderFormat = UIGraphicsImageRendererFormat.default()
            renderFormat.opaque = false
            let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
            newImage = renderer.image {
                (context) in
                image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
            }
        } else {
            UIGraphicsBeginImageContextWithOptions(CGSize(width: newSize.width, height: newSize.height), isOpaque, 0)
            image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
            newImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        }
    
        return newImage
    }
    

提交回复
热议问题