Swift 4.0 -
If you are dealing with images that contain transparencies, then the accepted answer function will actually convert the transparent areas to black.
If you want to scale and hold transparencies, try this feature:
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 }
abhimanyu jindal Aug 29 '17 at 10:32 on 2017-08-29 10:32
source share