How to rotate image in Swift?

后端 未结 13 1280
萌比男神i
萌比男神i 2020-11-30 03:55

I am unable to rotate the image by 90 degrees in swift. I have written below code but there is an error and doesn\'t compile

  func imageRotatedByDegrees(old         


        
13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 04:06

    Your code is not that far off from functional. You can apply the transform as you are doing directly to the bitmap, you don't need an intermediate view:

    func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -> UIImage {
        let size = oldImage.size
    
        UIGraphicsBeginImageContext(size)
    
        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: size.width / 2, y: size.height / 2)
        //Rotate the image context
        bitmap.rotate(by: (degrees * CGFloat(M_PI / 180)))
        //Now, draw the rotated/scaled image into the context
        bitmap.scaleBy(x: 1.0, y: -1.0)
    
        let origin = CGPoint(x: -size.width / 2, y: -size.width / 2)
    
        bitmap.draw(oldImage.cgImage!, in: CGRect(origin: origin, size: size))
    
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
    

    Also, if you're going to create a function that rotates an image, it is typically good form to include a clockwise: Bool parameter that will interpret the degrees argument as rotating clockwise or not. The implementation and appropriate conversion to radians I leave to you.

    Also note that it's a bit hand-wavy on my part to assume that oldImage.size is non-zero. If it is, force-unwrapping UIGraphicsGetCurrentContext()! will probably crash. You should validate the oldImage's size and if it's invalid just return oldImage.

提交回复
热议问题