我尝试使用下一个解决方案调整包含透明图像的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!
}
}
答案 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()
}
}