3

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();

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.

  • 2
    take a look at this: http://stackoverflow.com/questions/3539717/getting-a-screenshot-of-a-uiscrollview-including-offscreen-parts/3539944#3539944 – Mat Oct 16 '11 at 22:11
  • You're welcome...be aware that if you have an huge uiview(like a long tableview) to render, the method take much time to be executed. – Mat Oct 18 '11 at 13:48

1 Answers1

0

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 
    
Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393