Recently, while working on a project, I encountered the need to capture a specific area of the image. Most of them are done in Objective-C. Therefore, based on multiple references, Swift language is used for implementation, and the implementation method is recorded as follows:

import UIKit

extension UIImage {

    /// capture the specified area of the image and generate a new image
    /// -parameter rect: specifies the field
    func cropping(to rect: CGRect) -> UIImage? {
        let scale = UIScreen.main.scale
        let x = rect.origin.x * scale
        let y = rect.origin.y * scale
        let width = rect.size.width * scale
        let height = rect.size.height * scale
        let croppingRect = CGRect(x: x, y: y, width: width, height: height)
        // Take part of the image and generate a new image
        guard let sourceImageRef = self.cgImage else { return nil }
        guard let newImageRef = sourceImageRef.cropping(to: croppingRect) else { return nil }
        let newImage = UIImage(cgImage: newImageRef, scale: scale, orientation: .up)
        return newImage
    }

}

Copy the code