XZ_Swift 之把指定的view生成图片保存相册

商品详情页-生成海报分享,图片保存

// view生成图片的代码
extension UIView {
    // 生成传入的frame大小的图片
    public func xz_snapshot(ssFrame: CGRect) -> UIImage? {
        // 最后一个参数:scale 如果是1的话 保存的图片很模糊 适合分享用的, scale 是3 就是3x的图片 适合保存到本地
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 3)
        if UIGraphicsGetCurrentContext() != nil {
            drawHierarchy(in: ssFrame, afterScreenUpdates: true)
            let screenshot = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return screenshot
        }
        return nil
    }
    
    // 生成传入view的frame大小的图片
    public var xz_snapshotImage: UIImage? {
        // 最后一个参数:scale 如果是1的话 保存的图片很模糊 适合分享用的, scale 是3 就是3x的图片 适合保存到本地
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 3)
        if UIGraphicsGetCurrentContext() != nil {
            drawHierarchy(in: bounds, afterScreenUpdates: true)
            let screenshot = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return screenshot
        }
        return nil
    }

    /// Create snapshot
    ///
    /// - parameter rect: The `CGRect` of the portion of the view to return. If `nil` (or omitted),
    ///                   return snapshot of the whole view.
    ///
    /// - returns: Returns `UIImage` of the specified portion of the view.
    
    func snapshot(of rect: CGRect? = nil) -> UIImage? {
        // snapshot entire view
        
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: true)
        let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        // if no `rect` provided, return image of whole view
        
        guard let image = wholeImage, let rect = rect else { return wholeImage }
        
        // otherwise, grab specified `rect` of image
        
        let scale = image.scale
        let scaledRect = CGRect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale)
        guard let cgImage = image.cgImage?.cropping(to: scaledRect) else { return nil }
        return UIImage(cgImage: cgImage, scale: scale, orientation: .up)
    }
}


// 调用
if let image = viewBg.xz_snapshotImage {
    // 图片保存相册
}

你可能感兴趣的:(ios,swift)