Swift:旋转 UIImage 并填充它

问题描述

我目前正在旋转图像并快速填充它。 如果我使用下面的代码(我从互联网上得到的),我可以旋转图像,保持大小。 代码下方显示一个示例。 而且,问题是,我在旋转后的每个角落都有灰色间隙。 我想用白色填充它,使图像看起来不错。

有什么办法可以快速填补轮换后的空白?

谢谢!

extension UIImage {

    func rotatedBy(degree: CGFloat) -> UIImage {
        let radian = -degree * CGFloat.pi / 180
        UIGraphicsBeginImageContext(self.size)
        let context = UIGraphicsGetCurrentContext()!
        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
    }

}

enter image description here

解决方法

您只需要在旋转图像之前设置填充颜色并填充您的上下文:


extension UIImage {
    func rotatedBy(degree: CGFloat) -> UIImage? {
        guard let cgImage = cgImage else { return nil }
        UIGraphicsBeginImageContextWithOptions(size,false,0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        defer { UIGraphicsEndImageContext() }
        UIColor.white.setFill()
        context.fill(.init(origin: .zero,size: size))
        context.translateBy(x: size.width/2,y: size.height/2)
        context.scaleBy(x: 1,y: -1)
        context.rotate(by: -degree * .pi / 180)
        context.draw(cgImage,in: CGRect(origin: .init(x: -size.width/2,y: -size.height/2),size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}