SoFunction
Updated on 2025-04-14

iOS image cropping + rotation

Previously, the method of image cropping and image rotation was introduced separately

"iOS picture cropping method"

address:https:///article/

"iOS Picture Rotation Method"

address:https:///article/

Cropping and rotation can be performed together. First locate the area that needs to be cropped, then rotate the center of this area as the axis, and finally obtain the picture in this area after rotation. It can be implemented using bitmap (Bitmap) drawing

static func cropImage(_ image: UIImage, withRect rect: CGRect, angle: Double) -> UIImage? {
 // Creates a bitmap-based graphics context with rect size
 // and makes it the current context
 UIGraphicsBeginImageContext()
 // Get current graphics context
 guard let context = UIGraphicsGetCurrentContext() else { return nil }
 // Move context origin to rect center
 (x:  / 2, y:  / 2)
 // Convert angle to radian and rotate
 (by: CGFloat(angle / 180 * M_PI))
 // Move context origin back (- / 2, - / 2)
 // and move opposite direction of rect origin (-, -)
 (x: - / 2 - , y: - / 2 - )
 // Draw image at context origin
 (at: .zero)
 // Get image
 let finalImage = UIGraphicsGetImageFromCurrentImageContext()
 // Removes the current bitmap-based graphics context from the top of the stack
 UIGraphicsEndImageContext()
 // Return image
 return finalImage
}

rectFor the area that needs to be cropped, the coordinate system of the original image is used.angleThe angle to which you want to rotate is in degrees, and a positive value indicates that the picture rotates clockwise. See the comments on the specific implementation.

The last image may be beyond the original image area, and the excess is transparent.

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!