In my app and using Objective-C I need to implement the following functionality if possible. I would like to know if it is possible to generate a screenshot of the selected text from a UITextView. I know it sounds like a weird question but it is an important and a required functionality.

I know how to just create a screenshot programmatically but would like the region of the screenshot to be selectable based on the selected text, I hope you know what I mean.

Thank you.

2

There are 2 best solutions below

1
On BEST ANSWER

This code will help you:

NSString *selectedText = [textView textInRange:textView.selectedTextRange];
NSDictionary *textOptions = @{NSFontAttributeName : textView.font, NSForegroundColorAttributeName : textView.textColor};
CGSize textSize = [selectedText sizeWithAttributes:textOptions];

UIGraphicsBeginImageContextWithOptions(textSize, NO, 0);
[selectedText drawInRect:CGRectMake(0, 0, textSize.width, textSize.height) withAttributes:textOptions];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
2
On

I'm going to supposed your UITextView is self.textView, using quartz you can do:

UIGraphicsBeginImageContextWithOptions(self.textView.bounds.size, NO, 0.0);

[self.textView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *newImageWithMyTextView = UIGraphicsGetImageFromCurrentImageContext();

More info search Core Graphics in Apple docs