1. 程式人生 > >iOS 截圖, 獲得普通view和ScrollView的UIImage (Swift 4)

iOS 截圖, 獲得普通view和ScrollView的UIImage (Swift 4)

/****************************截圖**************************************/
//MARK: 截圖
///截圖 View
func screenImageWithView(cutView: UIView)-> UIImage {
    //截圖區域;是否透明;清晰度
    var image = UIImage()
    UIGraphicsBeginImageContextWithOptions(cutView.frame.size, true, UIScreen.main.scale)
    cutView.layer.render(in: UIGraphicsGetCurrentContext()!)
    image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsGetCurrentContext()
    return image
}

//MARK: 截圖scrollview
/// 截圖scrollview
func cutFullImageWithView(scrollView:UIScrollView) -> UIImage {
    // 記錄當前的scrollView的偏移量和座標
    let currentContentOffSet:CGPoint = scrollView.contentOffset
    let currentFrame:CGRect = scrollView.frame;
    
    // 設定為zero和相應的座標
    scrollView.contentOffset = CGPoint.zero
    scrollView.frame = CGRect.init(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
    
    // 引數①:截圖區域  引數②:是否透明  引數③:清晰度
    UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, true, UIScreen.main.scale)
    scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    
    // 重新設定原來的引數
    scrollView.contentOffset = currentContentOffSet
    scrollView.frame = currentFrame
    
    UIGraphicsEndImageContext()
    
    return image
}