You set the opaque property to true. If you want it to be transparent, you need to set it to false:
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
Note that UIGraphicsBeginImageContextWithOptions returns an optional image, so you must also change the return type, and you can use defer to end your context after returning the result:
extension UIImage { func resizeImageWith(newSize: CGSize) -> UIImage? { let horizontalRatio = newSize.width / size.width let verticalRatio = newSize.height / size.height let ratio = max(horizontalRatio, verticalRatio) let newSize = CGSize(width: size.width * ratio, height: size.height * ratio) UIGraphicsBeginImageContextWithOptions(newSize, false, 0) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: newSize)) return UIGraphicsGetImageFromCurrentImageContext() } }
source share