创建UITextView整个内容的位图 [英] Create bitmap of UITextView's entire content

查看:57
本文介绍了创建UITextView整个内容的位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取UITextView内容的位图.我可以使用以下方法获取当前在屏幕上显示的UITextView内容的位图:

I'm trying to get a bitmap of a UITextView's content. I'm able to get a bitmap of the UITextView's content that is currently on the screen with:

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

UIGraphicsEndImageContext();

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

But I want a bitmap of ALL the content, not just the content visible on the screen. Is this possible? Note that I don't want only the text of the UITextView, I want a bitmap of the content itself. I searched around and found how do do this in Android, with getDrawingCache, but couldn't find anything for objective c.

推荐答案

一种方法是制作UITextView的副本,然后将副本的大小调整为它的内容大小(只要内容大小更大)比框架的尺寸大).

One way to do this is to make a copy of the UITextView and then resize the copy to it's content size (as long as the content size is bigger than the frame size).

在Swift中,它看起来像这样:

In Swift it looks like this:

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
}

这使您可以获取所有内容的图像,甚至是无需滚动即可看到的部分.

This allows you to get an image of all of the content, even the part that in not visible without scrolling.

注释

  • 我的一般回答是此处.
  • textViewCopy只是框架和属性文本的副本.这应该足以获得完整图像.但是,如果由于某种原因需要更精确的副本,则可以执行以下操作:(解释)

  • My somewhat more general answer is here.
  • The textViewCopy is only a copy of the frame and the attributed text. That should be enough to get a full image. However, if for some reason a more exact copy is needed, then one could do the following: (explanation)

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

这篇关于创建UITextView整个内容的位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆