Resizing a transparent image (UIImage) without getting a black background

I tried resizing my UIImage that contains a transparent image using the following solution, but it returns an image without transparency, instead the transparent area turns black

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, true, 0) draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } 
0
source share
1 answer

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() } } 
+4
source

Source: https://habr.com/ru/post/1264915/


All Articles