Resize UIImage to 200x200pt/px

前端 未结 13 2081
后悔当初
后悔当初 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:45

    If you're dealing with PNG 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:

    SWIFT 4

    extension UIImage {
        func scaleImage(toSize newSize: CGSize) -> UIImage? {
            var newImage: UIImage?
            let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
            UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
            if let context = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage {
                context.interpolationQuality = .high
                let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height)
                context.concatenate(flipVertical)
                context.draw(cgImage, in: newRect)
                if let img = context.makeImage() {
                    newImage = UIImage(cgImage: img)
                }
                UIGraphicsEndImageContext()
            }
            return newImage
        }
    }
    

提交回复
热议问题