【问题标题】:Swift: Rotating UIImage and filling itSwift:旋转 UIImage 并填充它
【发布时间】:2021-08-04 18:09:54
【问题描述】:

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

有什么办法可以快速填补旋转后的空白吗?

谢谢!

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
    }

}

【问题讨论】:

  • 图片是图片或者背景不是白色怎么办?
  • 在我正在制作的应用程序中,所有背景都是白色的。所以,这不会是一个问题。此外,我还想知道快速填充颜色的一般方法,所以任何答案都会有所帮助!
  • 所以只需将颜色设置为白色并在绘制图像之前填充它
  • 谢谢!如果可能的话,我想知道使用什么样的代码。但是,您的回答仍然有很大帮助! :)
  • 是 context.setFillColor() 吗?

标签: ios swift xcode image-processing uiimage


【解决方案1】:

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


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()
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2021-08-26
    相关资源
    最近更新 更多