创建UITextView的整个内容的位图
我正在尝试获取UITextView内容的位图。 我能够获得当前屏幕上的UITextView内容的位图:
UIGraphicsBeginImageContext(myTextView.bounds.size); [myTextView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); myImageView.image=resultingImage; UIGraphicsEndImageContext();
但我想要一个所有内容的位图,而不仅仅是屏幕上可见的内容。 这可能吗? 请注意,我不只想要UITextView的文本,我想要一个内容本身的位图。 我在周围搜索并发现如何使用getDrawingCache在Android中执行此操作,但找不到任何针对目标c的内容。
一种方法是制作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 }
这使您可以获得所有内容的图像,甚至是不滚动而不可见的部分。
笔记
- 我的答案更为一般。
-
textViewCopy
只是框架和属性文本的副本。 这应该足以获得完整的图像。 但是,如果由于某种原因需要更精确的副本,则可以执行以下操作:( 说明 )let tempArchive = NSKeyedArchiver.archivedDataWithRootObject(textView) let textViewCopy = NSKeyedUnarchiver.unarchiveObjectWithData(tempArchive) as! UITextView