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).
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.
Notes
- 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