ios - 将 UITableView 捕获为图像 - 滚动

标签 ios objective-c swift uitableview uigraphicscontext

向下滚动表格时,我用于将 UITableView 捕获为图像的 Swift 代码无法正常工作。我基本上在 Objective-C 中找到了答案,但似乎无法使其在 Swift 中工作。目前这是我在 Swift 中拥有的:

func snapshotOfCell (inputView: UIView) -> UIView {
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
    inputView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
    UIGraphicsEndImageContext()
    let cellSnapshot : UIView = UIImageView(image: image)
    cellSnapshot.layer.masksToBounds = false

    return cellSnapshot
}

我找到了 this回答,但它在 Objective-C 中:

-(UIImage *) imageWithTableView:(UITableView *)tableView {
    UIView *renderedView = tableView;
    CGPoint tableContentOffset = tableView.contentOffset;
    UIGraphicsBeginImageContextWithOptions(renderedView.bounds.size, renderedView.opaque, 0.0);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(contextRef, 0, -tableContentOffset.y);
    [tableView.layer renderInContext:contextRef];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

它似乎通过使用 contentOffset 来解决滚动问题。但是,我一直试图将它集成到我的 Swift 函数中,但没有成功。有人擅长 Objective-C 和 Swift 吗?谢谢!

最佳答案

将整个表格 View 捕获为图像

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(tableView.contentSize.width, tableView.contentSize.height),false, 0.0)

    let context = UIGraphicsGetCurrentContext()

    let previousFrame = tableView.frame

    tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.contentSize.width, tableView.contentSize.height);

    tableView.layer.renderInContext(context!)

    tableView.frame = previousFrame

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();

    imageView.image = image;

在滚动位置抓取tableview的截图

    let contentOffset = tableView.contentOffset

    UIGraphicsBeginImageContextWithOptions(tableView.bounds.size, true, 1)

    let context = UIGraphicsGetCurrentContext()

    CGContextTranslateCTM(context, 0, -contentOffset.y)

    tableView.layer.renderInContext(context!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    imageView.image = image;

关于ios - 将 UITableView 捕获为图像 - 滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37049770/

相关文章:

iphone - 调用方式 - (CGFloat)tableView :(UITableView *)tableView heightForFooterInSection:(NSInteger)section without reloading

ios - 如何更改 UITableViewCell 的detailDisclosureButton 的按钮

javascript - Phonegap 应用程序 - iOS 上的 localStorage(需要说明)

iphone - 使用高斯模糊创建半透明的 UIView

android - 我可以在 android 中使用为 ios 创建的 sqlite 数据库吗?

c++ - 在 Objective-C 中使用 C++ 静态库

ios - 仅更改 NSAttributedString 的字体大小

swift - 在 swift 应用程序中以 root 身份运行命令

iphone - 以编程方式将所有 UITextField 和 UITextView 的委托(delegate)设置为 self

iOS 4.0 Twitter 集成