Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UIWebview contents to a UIImage

I am using a UIWebView to display HTML formatted text. I am not loading a webpage, just supplying a string of HTML to the UIWebView.

Now I want to animate this UIWebView on screen, actually several of them (2-10 at a time). UIWebView is a little heavy, and although I haven't attempted it yet, I am planning for the worst. (I don't think this is premature optimization, I 'm almost positive this will be an issue)

To get around the problem, I figured I could convert the contents of the UIWebViews to UIImages and animate them instead.

So, my questions are:

  1. How do you convert UIWebview contents to a UIImage (or CGImageRef)?
  2. My UIWebViews have transparent bacgrounds, will the transparency be carried over to the UIImage?

Thanks for any suggestions

like image 825
Corey Floyd Avatar asked May 13 '09 15:05

Corey Floyd


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How can I clear the contents of a UIWebView Wkwebview?

To clear old contents of webview With UIWebView you would use UIWebViewDelegate 's - webViewDidFinishLoad: .

How do you add a UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]];

How do I copy UIImage?

Deep copying UIImage *newImage = [UIImage imageWithData:UIImagePNGRepresentation(oldImage)]; This will copy the data but will require setting the orientation property before handing it to something like UIImageView for proper display. Another way to deep copy would be to draw into the context and grab the result.


1 Answers

UIGraphicsBeginImageContext(webview.bounds.size);
[webview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

You might run into issues if the webview dimensions are large because the webview uses a CATiledLayer that doesn't draw everything for memory reasons.

The image will include transparency

like image 114
Jason Harwig Avatar answered Oct 27 '22 00:10

Jason Harwig