views:

733

answers:

6

I am wondering how my iPhone app can take a screen shot of a specific UIView as a UIImage.

I tried this code but all I get is a blank image.

UIGraphicsBeginImageContext(CGSizeMake(320,480));
CGContextRef context = UIGraphicsGetCurrentContext();
[myUIView.layer drawInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

myUIView has dimensions 320x480 an it has some sub-views. What is the correct way to do this?

Thanks in advance.

A: 

The most likely cause is that the coordinate system isn't laid out the way you think it is. Check your geometry, you might be drawing outside the bounds of the newly-created context.

NSResponder
A: 
CGImageRef UIGetScreenImage();

Apple now allows us to use it in a public application, even though it's a private API

Matt S.
There are other UIViews on top of myUIView that I don't want to capture. Otherwise, this would be great.
cduck
+4  A: 

I think you may want renderInContext, not drawInContext. drawInContext is more a method you would override...

Note that it may not work in all views, specifically a year or so ago when I tried to use this with the live camera view it did not work.

Kendall Helmstetter Gelner
Thanks, it works.
cduck
A: 

Have a look at this stackoverflow question - Converting an UIview unto UIimage causing memory leak

epatel
+1  A: 
- (void)drawRect:(CGRect)rect {
  UIGraphicsBeginImageContext(self.bounds.size);    
  [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);  
}

This method may put in your Controller class.

A: 

Apple do not allow

CGImageRef UIGetScreenImage();

Now all application should take the screenshot like this or use above drawRect method http://developer.apple.com/library/ios/#qa/qa2010/qa1703.html

Adeem Maqsood Basraa