Skip to content

Instantly share code, notes, and snippets.

@YusukeHosonuma
Last active December 9, 2021 12:30
Show Gist options
  • Save YusukeHosonuma/5235d14f20077573c031dd780e2dbef0 to your computer and use it in GitHub Desktop.
Save YusukeHosonuma/5235d14f20077573c031dd780e2dbef0 to your computer and use it in GitHub Desktop.
Capture UITableView full content.
//
// ViewController.swift
// UIViewCapture
//
// Created by Yusuke on 11/7/16.
// Copyright © 2016 Yusuke. All rights reserved.
//
import UIKit
extension UIView {
func captureImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
guard let context: CGContext = UIGraphicsGetCurrentContext() else { return nil }
self.layer.render(in: context)
let capturedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return capturedImage
}
}
extension UITableView {
var contentBottom: CGFloat {
return contentSize.height - bounds.height
}
override func captureImage() -> UIImage? {
let images = captureImages()
// Concatenate images
UIGraphicsBeginImageContext(contentSize);
var y: CGFloat = 0
for image in images {
image.draw(at: CGPoint(x: 0, y: y))
y = min(y + bounds.height, contentBottom) // calculate layer diff
}
let concatImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return concatImage
}
func captureImages() -> [UIImage] {
var images: [UIImage?] = []
while true {
images.append(superview?.captureImage()) // not work in self.view
if contentOffset.y < (contentBottom - bounds.height) {
contentOffset.y += bounds.height
} else {
contentOffset.y = contentBottom
images.append(superview?.captureImage()) // not work in self.view
break
}
}
return images.flatMap{ $0 } // exclude nil
}
}
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let image = self.tableView.captureImage() {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(didFinishWriteImage(_:error:contextInfo:)), nil)
}
}
// MARK: - UIImageWriteToSavedPhotosAlbum
func didFinishWriteImage(_ image: UIImage, error: NSError?, contextInfo: UnsafeMutableRawPointer) {
if let error = error {
print("Image write error: \(error)")
}
}
// MARK: - UITableViewDataSource
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 60
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else { return UITableViewCell() }
cell.textLabel?.text = "Index: \(indexPath.row)"
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment