调整透明图像(UIImage)的大小而不会出现黑色背景

时间:2018-01-23 14:00:23

标签: 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!
    }
}

1 个答案:

答案 0 :(得分:4)

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

UIGraphicsBeginImageContextWithOptions(newSize, false, 0)

请注意,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()
    }
}