In my app I need to rotate an CGImage
by certain radians.
I already tried a few things but so far without success. The problem is that it seems like the context still draws the image in the old image width. The output picture does have the correct width, but instead of the image being fully drawn in that width, it seems to draw it in the center of that with the old image width.
To further visualise:
Initial Image
Current Solution Output
Expected Output
Here is the code I have so far
func fixOrientation(of cgImage: CGImage, by radians: CGFloat, orientationDidChange: Bool) -> CGImage? {
let imageWidth = CGFloat(cgImage.width)
let imageHeight = CGFloat(cgImage.height)
let newImageSize = orientationDidChange
? CGSize(width: imageHeight, height: imageWidth)
: CGSize(width: imageWidth, height: imageHeight)
guard let colorSpace = cgImage.colorSpace,
let context = CGContext(
data: nil,
width: Int(newImageSize.width),
height: Int(newImageSize.height),
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: cgImage.bitmapInfo.rawValue
)
else {
return nil
}
// Rotating image around it's own center
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: newImageSize.width / 2, y: newImageSize.height / 2)
transform = transform.rotated(by: radians)
transform = transform.translatedBy(x: -newImageSize.width / 2, y: -newImageSize.height / 2)
context.concatenate(transform)
context.draw(cgImage, in: .init(x: 0, y: 0, width: context.width, height: context.height))
return image
}
orientationDidChange
will be true for the case where the image has been taken in landscape.
Breakpoints suggest that newImageSize.width and context.width (and their respective heights) have the right, rotated values.
Res is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.