【问题标题】:Create bitmap of UITextView's entire content创建 UITextView 全部内容的位图
【发布时间】:2011-10-16 20:17:56
【问题描述】:

我正在尝试获取 UITextView 内容的位图。我可以通过以下方式获取当前屏幕上 UITextView 内容的位图:

UIGraphicsBeginImageContext(myTextView.bounds.size);
[myTextView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
myImageView.image=resultingImage;

UIGraphicsEndImageContext();

但我想要所有内容的位图,而不仅仅是屏幕上可见的内容。这可能吗?请注意,我不仅想要 UITextView 的文本,还想要内容本身的位图。我四处搜索,发现如何在 Android 中使用 getDrawingCache 执行此操作,但找不到目标 c 的任何内容。

【问题讨论】:

  • 正是我需要的@Mat 非常感谢!
  • 不客气……请注意,如果要渲染一个巨大的 uiview(如长 tableview),则该方法需要很长时间才能执行。

标签: iphone objective-c ios


【解决方案1】:

一种方法是制作UITextView 的副本,然后将副本的大小调整为其内容大小(只要内容大小大于帧大小)。

在 Swift 中是这样的:

func imageFromTextView(textView: UITextView) -> UIImage {

    // Make a copy of the textView first so that it can be resized 
    // without affecting the original.
    let textViewCopy = UITextView(frame: textView.frame)
    textViewCopy.attributedText = textView.attributedText

    // resize if the contentView is larger than the frame
    if textViewCopy.contentSize.height > textViewCopy.frame.height {
        textViewCopy.frame = CGRect(origin: CGPointZero, size: textViewCopy.contentSize)
    }

    // draw the text view to an image
    UIGraphicsBeginImageContextWithOptions(textViewCopy.bounds.size, false, UIScreen.mainScreen().scale)
    textViewCopy.drawViewHierarchyInRect(textViewCopy.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

这使您可以获取所有内容的图像,甚至是不滚动不可见的部分。

备注

  • 我比较笼统的回答是here
  • textViewCopy 只是框架和属性文本的副本。这应该足以获得完整的图像。但是,如果出于某种原因需要更精确的副本,则可以执行以下操作:(explanation)

    let tempArchive = NSKeyedArchiver.archivedDataWithRootObject(textView)
    let textViewCopy = NSKeyedUnarchiver.unarchiveObjectWithData(tempArchive) as! UITextView 
    

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多