chestnutforest
chestnutforest

Reputation: 33

Swift: Rotating UIImage and filling it

I am currently working on rotating an image and filling it with swift. If I use the code below (which I got from the internet) I can rotate an image, keeping size. An example is illustrated below the code. And, the problem is, I have a gray gap in every corner after the rotation. I want to fill it with white so that image looks nice.

Is there any way to fill the gap after the rotation in swift?

Thank you!

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

Upvotes: 1

Views: 988

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

You just need to set a fill color and fill your context before rotating the image:


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

Upvotes: 2

Related Questions