iOS Picture Cropping + Rotation
- 2021-11-13 18:28:07
- OfStack
Before, we introduced the methods of picture cropping and picture rotation respectively
[iOS Picture Cropping Method]
Address: https://www.ofstack.com/article/107308. htm
"iOS Image Rotation Method"
Address: https://www.ofstack.com/article/107361. htm
Cropping and rotation can be performed in one place. First, locate the area to be clipped, then take the center of this area as the axis, rotate 1 fixed angle, and finally get the picture in this area after rotation. It can be realized by 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(rect.size)
// Get current graphics context
guard let context = UIGraphicsGetCurrentContext() else { return nil }
// Move context origin to rect center
context.translateBy(x: rect.width / 2, y: rect.height / 2)
// Convert angle to radian and rotate
context.rotate(by: CGFloat(angle / 180 * M_PI))
// Move context origin back (-rect.width / 2, -rect.height / 2)
// and move opposite direction of rect origin (-rect.minX, -rect.minY)
context.translateBy(x: -rect.width / 2 - rect.minX, y: -rect.height / 2 - rect.minY)
// Draw image at context origin
image.draw(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
}
rect is the area that needs to be cut, and adopts the coordinate system of the original drawing. angle is the angle to be rotated in degrees, and a positive value indicates that the picture rotates clockwise. See the notes for the explanation of the specific implementation.
The final image may exceed the original image area, and the excess is transparent.