首页 > 解决方案 > 如何获取 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
    }
}

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

这是我的UITextViewWith Frame(0.0, 97.0, 414.0, 234.0) 在此处输入图像描述

这是使用pb_takeSnapshot()With Framewidth = 414.0, height = 234.0 的快照图像在此处输入图像描述

标签: iosswiftuiviewuiimageuitextview

解决方案


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

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

创建矩形以从头开始绘制:

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

推荐阅读