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

前端 未结 6 682
难免孤独
难免孤独 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 16:47

    The highlighted state of a UIButton did not take the correct orientation of the normal inserted turned image. So I had to redraw the image like @RyanG showed. Here is the Swift 2.2 code for that:

    extension UIImage
    {
        /// Rotate an image by any given radians.
        /// Works for 2x and 3x retina as well.
        func imageRotatedByDegrees(degrees: Double) -> UIImage
        {
            let radians = CGFloat(degrees * (M_PI / 180.0))
    
            let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: self.size))
            let t: CGAffineTransform = CGAffineTransformMakeRotation(radians)
            rotatedViewBox.transform = t
            let rotatedSize = rotatedViewBox.frame.size
    
            UIGraphicsBeginImageContextWithOptions(rotatedSize, false, self.scale)
            let bitmap = UIGraphicsGetCurrentContext()
    
            CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2)
            CGContextRotateCTM(bitmap, radians)
            CGContextScaleCTM(bitmap, 1.0, -1.0)
            CGContextDrawImage(bitmap, CGRect(origin: CGPoint(x: -self.size.width / 2, y: -self.size.height / 2), size: self.size), self.CGImage)
    
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage
        }
    }
    

提交回复
热议问题