最近在做项目的时候,遇到了需要截取图片指定区域的需求。经查找,绝大多数都是通过Objective-C 语言实现的。所以多方参考下,用 Swift 语言进行了实现,现将实现方式记录如下:
import UIKit
extension UIImage {
/// 截取图片的指定区域,并生成新图片
/// - Parameter rect: 指定的区域
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)
// 截取部分图片并生成新图片
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
}
}