10

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

Corey Floyd
  • 25,929
  • 31
  • 126
  • 154

2 Answers2

21
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

Jason Harwig
  • 43,743
  • 5
  • 43
  • 44
  • Thanks.My webviews are just simple single lines of text, so I don't think that will be an issue. I guess the dimensions of the image are the dimensions of the webview on screen? – Corey Floyd May 13 '09 at 17:05
  • You might need to call sizeToFit: after the webview loads, to get the webview the exact size of the content – Jason Harwig May 13 '09 at 19:06
  • just out of curiosity why do you want to display single lines of text as UIWebView? – Thomas Sep 14 '10 at 07:01
  • I've asked a followup question concerning how to deal with large webview dimension. It can be found here: http://stackoverflow.com/q/4475397/516731 – Matt Blackmon Dec 17 '10 at 22:49
  • now what do you do if you need to put in that image something other than the webview? turn it first to image and then aggregate or is there a more elegant way? – Lior Frenkel Apr 30 '11 at 04:55
  • Nice, but the resulting image, is not that crisp... I wonder if there is a way to enlarge the resolution of the image (like using something like scale = 2, so you get a more crisp image)... – Gik Jan 15 '16 at 23:18
  • Maybe this: UIGraphicsBeginImageContextWithOptions(webview.bounds.size, NO, 0); works better... – Gik Jan 15 '16 at 23:25
0

I could be wrong but if you set the cache param of CoreAnimation the OS will handle this optimisation for you.

e.g.

[UIView setAnimationTransition:transition forView:self.view cache:YES];
  • I'm doing a path animation, so I can't use UIView convenience methods, but their may be something (probably is) in CA that works simalarly... – Corey Floyd May 14 '09 at 01:38