tags:

views:

64

answers:

1

I use the following code to get a screenshot of the screen and save it to the photo albums.

 CGImageRef screen = UIGetScreenImage();
        UIImage *screenImage = [UIImage imageWithCGImage:screen];
    UIImageWriteToSavedPhotosAlbum(screenimage, nil, nil), nil);

This works great but if my app is in landscape mode the saved image does not come out right. (in needs a 90 degree turn). What do i need to do?

A: 

Test for either

[UIDevice currentDevice].orientation == UIInterfaceOrientationLandscapeRight
[UIDevice currentDevice].orientation == UIInterfaceOrientationLandscapeLeft
(and possibly more orientations)

Then do the appropriate transformations to the image.

This can be done in several ways, this one doesn't take a lot of code:

/// click action saves orientation & picture:
-(void)screenshot
{
    self.orientationWhenPicked = [UIDevice currentDevice].orientation;
    CGImageRef screen = UIGetScreenImage();
    self.image = [UIImage imageWithCGImage:screen];
    CGImageRelease(screen);
}

/// somewhere else we are called for the image
-(void)getScreenshot
{
    UIDeviceOrientation useOrientation = self.orientationWhenPicked;
    UIImage *img = self.image;

    UIGraphicsBeginImageContext(CGSizeMake(480.0f, 320.0f));
    CGContextRef context = UIGraphicsGetCurrentContext();
    if ( useOrientation == UIDeviceOrientationLandscapeRight )
    {
            CGContextRotateCTM (context, M_PI/2.0f);
            [img drawAtPoint:CGPointMake(0.0f, -480.0f)];
    } else {
            CGContextRotateCTM (context, -M_PI/2.0f);
            [img drawAtPoint:CGPointMake(-320.0f, 0.0f)];
    }
    return UIGraphicsGetImageFromCurrentImageContext();
}

I modified it a little before posting to make it self-contained, but it should work with a little effort (e.g. create self.image etc). You may just blend them into one function.

mvds
Thanks so much! Can you please explain what this line does: [img drawAtPoint:CGPointMake(-320.0f, 0.0f)];And what it has to do with the rotation?Thanks in advance,-David
bobbypage
That's the line that puts the original image in the new image context. The `(-320,0)` coordinates make sure you cover the entire screen after rotation around (0,0).
mvds