我正在尝试获取 UITextView 内容的位图。我能够获取当前在屏幕上的 UITextView 内容的位图:
UIGraphicsBeginImageContext(myTextView.bounds.size);
[myTextView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
myImageView.image=resultingImage;
UIGraphicsEndImageContext();
但我想要所有内容的位图,而不仅仅是屏幕上可见的内容。这可能吗?请注意,我不只想要 UITextView 的文本,我想要内容本身的位图。我四处搜索,发现如何使用 getDrawingCache 在 Android 中执行此操作,但找不到 objective-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
}
这允许您获取所有内容的图像,即使是不滚动不可见的部分。
注意事项
- 我的答案是 here .
textViewCopy
只是框架和属性文本的副本。这应该足以获得完整的图像。但是,如果出于某种原因需要更精确的副本,则可以执行以下操作:( explanation )let tempArchive = NSKeyedArchiver.archivedDataWithRootObject(textView) let textViewCopy = NSKeyedUnarchiver.unarchiveObjectWithData(tempArchive) as! UITextView
关于iphone - 创建 UITextView 全部内容的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7787027/