You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中UIImage旋转后出现灰色边角间隙 如何将其填充为白色

Swift UIImage旋转边角间隙填充解决方案

你遇到的灰色间隙本质是图形上下文默认的透明区域在渲染时的显示效果,只需要在绘制旋转图片前,预先将整个画布填充为白色即可,修改后的完整代码如下:

extension UIImage {
    func rotatedBy(degree: CGFloat) -> UIImage {
        let radian = -degree * CGFloat.pi / 180
        // 替换原上下文创建方法,指定不使用透明通道、自动适配设备屏幕倍率
        UIGraphicsBeginImageContextWithOptions(self.size, true, 0)
        let context = UIGraphicsGetCurrentContext()!
        
        // 新增:先填充整个画布为白色
        UIColor.white.setFill()
        context.fill(CGRect(origin: .zero, size: self.size))
        
        context.translateBy(x: self.size.width / 2, y: self.size.height / 2)
        context.scaleBy(x: 1.0, y: -1.0)

        context.rotate(by: radian)
        context.draw(self.cgImage!, in: CGRect(x: -(self.size.width / 2), y: -(self.size.height / 2), width: self.size.width, height: self.size.height))

        let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return rotatedImage
    }
}

改动说明

  • 替换UIGraphicsBeginImageContext为UIGraphicsBeginImageContextWithOptions,第二个参数opaque设为true表示不需要透明通道,既匹配填充白色背景的需求,也能提升渲染性能;第三个参数scale传0会自动适配当前设备的屏幕倍率,避免生成的图片出现模糊问题。
  • 新增了白色背景填充逻辑,该操作在所有绘制动作之前执行,未被旋转后图片覆盖的边角区域会保留白色填充,不会再出现灰色间隙。

内容的提问来源于stack exchange,提问作者chestnutforest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 19:27:05