How Can I Rotate A UIImage and Image Data By 90 Degrees

前端 未结 6 672
难免孤独
难免孤独 2021-02-09 16:09

I have a UIImageView that contains an image. At the minute the user can click to save the image within the UIImageView to disk.

I would like to make it so that the the

6条回答
  •  别那么骄傲
    2021-02-09 17:10

    Swift version made from answer of @RyanG with some fixes:

    func rotated(by degrees: CGFloat) -> UIImage {
        let radians : CGFloat = degrees * CGFloat(.pi / 180.0)
        let rotatedViewBox = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let t = CGAffineTransform(rotationAngle: radians)
        rotatedViewBox.transform = t
        let rotatedSize = rotatedViewBox.frame.size
        UIGraphicsBeginImageContextWithOptions(rotatedSize, false, self.scale)
        defer { UIGraphicsEndImageContext() }
        guard let bitmap = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage else {
          return self
        }
        bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
        bitmap.rotate(by: radians)
        bitmap.scaleBy(x: 1.0, y: -1.0)
        bitmap.draw(cgImage, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
        guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else {
          return self
        }
        return newImage
      }
    

提交回复
热议问题