UIGraphicsGetImageFromCurrentImageContext() 在 UITableViewCell 中返回空白图像

Sup*_*rah 5 uitableview ios uigraphicscontext swift

我已经成功地使用下面的函数来拍摄 UIView 的快照,但是,现在我在 UITableViewCell 中使用它,它不再起作用。

static func pictureTaker(_ rawView: UIView) -> UIImageView {
        UIGraphicsBeginImageContextWithOptions(rawView.bounds.size, false, 0)
        rawView.drawHierarchy(in: rawView.bounds, afterScreenUpdates: true)
        let screenshot = UIGraphicsGetImageFromCurrentImageContext();
        let viewImage = UIImageView(image: screenshot)
        UIGraphicsEndImageContext();
        viewImage.frame = rawView.frame
        return viewImage
    }
Run Code Online (Sandbox Code Playgroud)

这是我用来填充 UITableViewCell 的函数的精简版本。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = gamesHolder.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as! StandardGameCell
        let row = indexPath.row

        let boardPreviewTemplate = UIView(frame: CGRect(x: 0, y: 0, width: cell.previewBoard.frame.width, height: cell.previewBoard.frame.height))
        GameManagement.setupBoard(boardPreviewTemplate, boardItems: gamesArray[row].board)

        let gamePicture = PageManagement.pictureTaker(boardPreviewTemplate)
        gamePicture.frame = CGRect(x: 0, y: 0, width: gamePicture.frame.width, height: gamePicture.frame.height)

        //Removing preview board items and replacing with picture
        cell.previewBoard.subviews.forEach({ $0.removeFromSuperview() })
        cell.previewBoard.addSubview(gamePicture)

        return cell
    }
Run Code Online (Sandbox Code Playgroud)

在上面的tableView函数中,我以编程方式创建一个新视图来复制cell.previewBoard,但我也尝试直接快照cell.previewBoard,但这也不起作用。我认为这个问题与 UITableViewCell 加载的时间有关。

我也 100% 肯定该函数正在返回一张图像(但是是一张空白图像),并且这就是我想要的位置。如果我更改UIGraphicsBeginImageContextWithOptions(rawView.bounds.size, false, 0)UIGraphicsBeginImageContextWithOptions(rawView.bounds.size, true, 0),返回的图像将显示为全黑。

最后一点,我发现这boardPreviewPicture.snapshotView(afterScreenUpdates: true)会返回一个图像,但它使得 UITableView 的滚动速度非常慢。也许我可以使用另一种解决方法snapshotView()

yon*_*nja 4

我遇到了同样的问题。我注意到,当UIGraphicsBeginImageContextWithOptions调用 inside时tableView(_:cellForRowAt:),结果UIGraphicsGetImageFromCurrentImageContext()是空白的。请注意,文档中指出UIGraphicsGetImageFromCurrentImageContext

可以从应用程序的任何线程调用此函数。

但是,我发现的解决方案是在主线程内调用它。对于你的情况,也许你可以这样做:

DispatchQueue.main.async {
    let gamePicture = PageManagement.pictureTaker(boardPreviewTemplate)
    gamePicture.frame = CGRect(x: 0, y: 0, width: gamePicture.frame.width, height: gamePicture.frame.height)

    //Removing preview board items and replacing with picture
    cell.previewBoard.subviews.forEach({ $0.removeFromSuperview() })
    cell.previewBoard.addSubview(gamePicture)
}
Run Code Online (Sandbox Code Playgroud)