Swift中如何缩放图片且不添加额外背景
解决Swift缩放图片保留透明背景的问题
你提到的缩放方法会给带透明通道的图片添加黑/白色背景,核心原因是旧的绘图上下文处理透明的方式不够可靠,或者缺少显式的透明背景设置。以下是两种可行的解决方案:
方案一:使用UIGraphicsImageRenderer(iOS 10+推荐)
这是苹果官方推荐的绘图API,能自动处理图片缩放比例和透明通道,避免背景问题:
func resizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage? { let size = image.size let widthRatio = targetSize.width / size.width let heightRatio = targetSize.height / size.height let newSize: CGSize if widthRatio > heightRatio { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } let renderer = UIGraphicsImageRenderer(size: newSize) return renderer.image { context in image.draw(in: CGRect(origin: .zero, size: newSize)) } }
方案二:兼容iOS 10以下的修改版
如果你需要兼容更低版本的系统,可以在原有代码基础上添加透明背景填充,确保上下文完全透明:
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? { let size = image.size let widthRatio = targetSize.width / size.width let heightRatio = targetSize.height / size.height var newSize: CGSize if widthRatio > heightRatio { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } UIGraphicsBeginImageContextWithOptions(newSize, false, image.scale) defer { UIGraphicsEndImageContext() } // 显式填充透明背景 UIColor.clear.setFill() UIRectFill(CGRect(origin: .zero, size: newSize)) image.draw(in: CGRect(origin: .zero, size: newSize)) return UIGraphicsGetImageFromCurrentImageContext() }
额外注意事项
如果缩放后的图片保存为JPG格式,由于JPG本身不支持透明通道,会自动用白色填充背景。若要保留透明,需将图片保存为PNG格式。
内容的提问来源于stack exchange,提问作者user21757794
相关产品推荐
相关产品推荐

