5

From what I've read, iOS7's new drawViewHierarchyInRect is supposed to be faster than CALayer's renderInContext. And according to this and this, it should be a simple matter of calling:

[myView drawViewHierarchyInRect:myView.frame afterScreenUpdates:YES];

instead of

[myView.layer renderInContext:UIGraphicsGetCurrentContext()];

However, when I try this, I just get blank images. Full code that does the capture, where "self" is a subclass of UIView,

        // YES = opaque. Ignores alpha channel, so less memory is used.
        // This method for some reasons renders the
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, self.window.screen.scale);    // Still slow.

    if ( [AIMAppDelegate isOniOS7OrNewer] )
        [self drawViewHierarchyInRect:self.frame afterScreenUpdates:YES]; // Doesn't work!
    else
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];     // Works!

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    contentImageView.image = image; // this is empty if done using iOS7's way

and contentImageView is a UIImageView that is added as a subView to self during initialization.

Additionally, the drawing that I want captured in the image is contained in other sub-views that are also added to self as a sub-view during initialization (including contentImageView).

Any ideas why this is failing when using drawViewHierarchyInRect?

* Update *

I get an image if I draw a specific sub-view, such as:

[contentImageView drawViewHierarchyInRect:contentImageView.frame afterScreenUpdates:YES];

or

[self.curvesView drawViewHierarchyInRect:self.curvesView.frame afterScreenUpdates:YES];

however I need all the visible sub-views combined into one image.

Community
  • 1
  • 1
Vern Jensen
  • 3,449
  • 6
  • 42
  • 59

1 Answers1

6

Try it with self.bounds rather than self.frame—it’s possible you’re getting an image of your view rendered outside the boundaries of the image context you’ve created.

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
  • Haha, through experimentation I just found the same result. That was the issue! Thanks. – Vern Jensen Nov 06 '13 at 21:31
  • Only other weird thing is that drawViewHierarchyInRect is actually a good bit SLOWER than renderInContext. I thought it should be faster? Any idea why it's not? – Vern Jensen Nov 06 '13 at 22:25
  • Might be the `afterScreenUpdates:YES`—I believe that forces it to wait for the next time the layer tree gets presented. Does the speed change if you turn that off? – Noah Witherspoon Nov 06 '13 at 22:29
  • In my case, some times `drawViewHierarchyInRect:afterScreenUpdates:` returns NO. I get the same result by using both self.frame and self.bounds. However, my issue is solved by using `renderInContext` as told by @VernJensen above. Thanks. – Lisarien Aug 27 '15 at 12:57