public extension UIView {
// 截取全图
func snapshotImage(afterUpdates: Bool) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: afterUpdates)
let snap = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snap
}
// 截取指定区域图
func snapshotImage(in rect: CGRect, afterUpdates: Bool, scale: CGFloat = UIScreen.main.scale) -> UIImage? {
let realRect = CGRect(x: rect.minX*scale, y: rect.minY*scale, width: rect.width*scale, height: rect.height*scale)
let image = snapshotImage(afterUpdates: afterUpdates)
guard let cgImage = image?.cgImage?.cropping(to: realRect) else { return nil }
return UIImage(cgImage: cgImage)
}
}
网友评论