Losing image orientation while converting an image to CGImage

后端 未结 7 2104
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 04:30

I\'m facing an image orientation issue when cropping a square portion of an image out of a rectangular original image. When image is in landscape, it\'s fine. But when it is

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 05:07

    SWIFT 5. I added the following as an extension to UIImage. Idea is to force the image inside you UIImage to match that of the UIImage orientation (which only plays a role in how it's displayed on the UI!). Redrawing the actual image data inside the UIImage "container" will make the corresponding CGImage has the same orientation

    func forceSameOrientation() -> UIImage {
        UIGraphicsBeginImageContext(self.size)
        self.draw(in: CGRect(origin: CGPoint.zero, size: self.size))
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            return self
        }
        UIGraphicsEndImageContext()
        return image
    }
    

提交回复
热议问题