UIView、UIScrollView、UITableView界面截图

UIView、UIScrollView截图:

extension UIView {
    func screenshot() -> UIImage {

            if(self is UIScrollView) {
                let scrollView = self as! UIScrollView

                let savedContentOffset = scrollView.contentOffset
                let savedFrame = scrollView.frame

                UIGraphicsBeginImageContext(scrollView.contentSize)
                scrollView.contentOffset = .zero
                self.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
                self.layer.render(in: UIGraphicsGetCurrentContext()!)
                let image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext();

                scrollView.contentOffset = savedContentOffset
                scrollView.frame = savedFrame

                return image!
            }

            UIGraphicsBeginImageContext(self.bounds.size)
            self.layer.render(in: UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image!

        }
}

UITableView:

func screenshot() -> UIImage{
    var image = UIImage();
    UIGraphicsBeginImageContextWithOptions(self.tableView.contentSize, false, UIScreen.main.scale)

    // save initial values
    let savedContentOffset = self.tableView.contentOffset;
    let savedFrame = self.tableView.frame;
    let savedBackgroundColor = self.tableView.backgroundColor

    // reset offset to top left point
    self.tableView.contentOffset = CGPoint(x: 0, y: 0);
    // set frame to content size
    self.tableView.frame = CGRect(x: 0, y: 0, width: self.tableView.contentSize.width, height: self.tableView.contentSize.height);
    // remove background
    self.tableView.backgroundColor = UIColor.clear

    // make temp view with scroll view content size
    // a workaround for issue when image on ipad was drawn incorrectly
    let tempView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.contentSize.width, height: self.tableView.contentSize.height));

    // save superview
    let tempSuperView = self.tableView.superview
    // remove scrollView from old superview
    self.tableView.removeFromSuperview()
    // and add to tempView
    tempView.addSubview(self.tableView)

    // render view
    // drawViewHierarchyInRect not working correctly
    tempView.layer.render(in: UIGraphicsGetCurrentContext()!)
    // and get image
    image = UIGraphicsGetImageFromCurrentImageContext()!;

    // and return everything back
    tempView.subviews[0].removeFromSuperview()
    tempSuperView?.addSubview(self.tableView)

    // restore saved settings
    self.tableView.contentOffset = savedContentOffset;
    self.tableView.frame = savedFrame;
    self.tableView.backgroundColor = savedBackgroundColor

    UIGraphicsEndImageContext();

    return image
}

你可能感兴趣的:(UIView、UIScrollView、UITableView界面截图)