在没有黑色背景的情况下调整透明图像 (UIImage) 的大小

use*_*924 0 ios swift

我尝试使用下一个解决方案调整包含透明图像的 UIImage 的大小,但它返回没有透明度的图像,而不是该透明区域变为黑色

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!
    }
}
Run Code Online (Sandbox Code Playgroud)

Leo*_*bus 5

您将 opaque 属性设置为 true。如果您希望它是透明的,则需要将其设置为 false:

UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
Run Code Online (Sandbox Code Playgroud)

请注意,UIGraphicsBeginImageContextWithOptions返回一个可选图像,因此您也应该更改返回类型,并且您可以在返回结果后使用 defer 结束上下文:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)