Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture current view screenshot and reuse in code? (iPhone SDK)

I am attemting to transition from one UIView to another, when the user rotates the device. This, in of itself, is not difficult. However, since I am displaying completely different content after the rotation, the default animation provided by UIKit (rotating the currently displayed view) is inappropriate conceptually.

Simply disabling the animation and swapping the views suddenly is tolerable, but is far below the polish I'm building into the rest of the app. What I would prefer to do is this:

When shouldAutorotateToInterfaceOrientation: is called, I would like to grab an opaque view snapshot, a screenshot if you will, of the user view before rotation. Then after the rotation is completed and the system has applied the view transforms etc, I can show the snapshot view I saved and animate a transition of my choice to my new view. After it is completed, I can release my snapshot and move on.

Is there a way to do this that is not expensive?

The only other option I can think of is to return NO on all orientations other than my default one, and then react by applying my own animations and transforms. I'd prefer to use the system to do this however, as I feel it is likely doing it myself could cause "undefined" keyboard behavior in the manually rotated view, etc.

Thoughts?

like image 789
Carson C. Avatar asked May 18 '09 18:05

Carson C.


2 Answers

- (UIImage *)captureView:(UIView *)view {
    CGRect screenRect = [[UIScreen mainScreen] bounds];

    UIGraphicsBeginImageContext(screenRect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);

    [view.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

Found this here :

http://discussions.apple.com/thread.jspa?messageID=8358740

like image 117
Sunil Phani Manne Avatar answered Oct 13 '22 10:10

Sunil Phani Manne


This code worked for me

- (UIImage *)captureScreenInRect:(CGRect)captureFrame {
    CALayer *layer;
    layer = self.view.layer;
    UIGraphicsBeginImageContext(self.view.bounds.size); 
    CGContextClipToRect (UIGraphicsGetCurrentContext(),captureFrame);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage;
}
like image 39
Mohith Km Avatar answered Oct 13 '22 08:10

Mohith Km