Screenshot Using UIGraphicsBeginImageContextWithOptions For iPad 3 (Retina)

4.8k Views Asked by At

I am taking a screenshot using the following code:

    // Returns 1024x768 for iPad Retina
    CGSize screenDimensions = [[UIScreen mainScreen] bounds].size;

    // Create a graphics context with the target size
    // (last parameter takes scale into account)
    UIGraphicsBeginImageContextWithOptions(screenDimensions, NO, 0);

    // Render the view to a new context
    CGContextRef context = UIGraphicsGetCurrentContext();
    [myView.layer renderInContext:context];

    // Save to Camera Roll
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIImageWriteToSavedPhotosAlbum(screenshot, self, nil, nil);

    UIGraphicsEndImageContext();

This works, however I have a report from a user that this results in an image in the Camera Roll that is not at the iPad retina resolution. Rather it looks more like the iPad non-retina resolution. (I don't have an iPad 3 to test this on).

Is there anything else that I am doing wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

So I finally got a hold of a physical iPad Retina, and the code that I posted originally works fine. The resulting image does appear to be at the full Retina resolution.

0
On

Here is the code that I'm using and I don't seem to have any issues with the iPad 3. You can also confirm using the retina iPad in the iOS Simulator. My code is also saving the file to the documents directory. You can modify it how you see fit.

    CGSize screenSize = [[UIScreen mainScreen] applicationFrame].size;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(nil, screenSize.width, screenSize.height, 8, 4*(int)screenSize.width, colorSpaceRef, kCGImageAlphaPremultipliedLast);
    CGContextTranslateCTM(ctx, 0.0, screenSize.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    [(CALayer*)self.view.layer renderInContext:ctx];

    CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpaceRef);
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/myscreenshot.jpg", docDir];

    [UIImageJPEGRepresentation(image, 1.0) writeToFile:filePath atomically:YES];