Rotate UIImage in swift

后端 未结 8 1445
一整个雨季
一整个雨季 2021-02-04 10:35

I want to rotate UIImage in clockwise direction. But my current code do not perform function accurate some time it rotate and some time its skip rotation. I want my UIImage will

8条回答
  •  逝去的感伤
    2021-02-04 10:46

    I fixed first function of @gleb's answer little bit. Size calculation is not necessary there. We simply should do it with reverse. Because if you do it size of 1149 x 356 with @gleb's function then you will get image sized 357 x 1149.

        extension UIImage {
    
            public func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
                let rotatedSize: CGSize = CGRect(x: 0, y: 0, width: self.size.height, height: self.size.width).size
    
                //Create the bitmap context
                UIGraphicsBeginImageContext(rotatedSize)
                let bitmap: CGContext = UIGraphicsGetCurrentContext()!
                //Move the origin to the middle of the image so we will rotate and scale around the center.
                bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
                //Rotate the image context
                bitmap.rotate(by: (degrees * CGFloat.pi / 180))
                //Now, draw the rotated/scaled image into the context
                bitmap.scaleBy(x: 1.0, y: -1.0)
                bitmap.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
    
                let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    
                UIGraphicsEndImageContext()
                return newImage
            }
        }
    

提交回复
热议问题