如何获取 UITextView 的完整快照

How To Take Full Snapshot Of UITextView

我正在尝试使用以下代码拍摄 UITextView 的快照

extension UIView {

    func pb_takeSnapshot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
        drawHierarchy(in: self.frame, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

但我给了我一半快照。当我使用 print 检查时,甚至 UITextViewSnapshot 图像也具有相同的 widthheight。我也尝试了不同的代码但没有奏效。谁能告诉我如何修复它,我想要 UITextView.

的完整快照

这是我的 UITextViewFrame (0.0, 97.0, 414.0, 234.0)

这是使用 pb_takeSnapshot()Frame 宽度 = 414.0,高度 = 234.0 的快照图像

你不应该使用 frame 来画图(出于某种原因,正如你在评论中所说)你的 bounds 没有给出正确的值。

如果不查看您的视图层次结构,很难调试其中的原因,但是您应该仍然能够创建正确的快照。

改为从头开始创建要绘制的矩形:

let rect = CGRect(x: 0.0, y: 0.0, width: bounds.size.width, height: bounds.size.height)
drawHierarchy(in: rect, afterScreenUpdates: true)