renderInContext on retina and non-retina devices
Asked Answered
F

1

7

I am creating a PDF by taking a screenshot of a UIView, this is currently working great on the iPad3 with the retina display, but when testing on other devices with lower resolution screens I am having problems with text resolution.

Here is my code:

    //start a new page with default size and info
    //this can be changed later to include extra info.
    UIGraphicsBeginPDFPage();

    //render the view's layer into an image context
    //the last option specifies scale. If 0, it uses the devices scale.
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 2.0);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //render the screenshot into the pdf page CGContext
    [screenShot drawInRect:view.bounds];

    //close the pdf context (saves the pdf to the NSData object)
    UIGraphicsEndPDFContext();

I have also tried to set the UIGraphicsBeginImageContextWithOptions scale to 2.0, but this gives no change. How can I force a view on an iPad2 to render at 2x resolution?

Expected output:

Imgur

Actual output:

Imgur

Felicafelicdad answered 5/11, 2012 at 3:32 Comment(3)
What problems are you having? Setting the scale in UIGraphicsBeginImageContextWithOptions to 2 should force it to render at 2x resolution. Post images showing the correct and incorrect outputs.Selestina
Are those screenshots of the PDF? The two images are different sizes, but one's not twice the dimensions of the other. Nor does one look like it was rendered at twice the resolution of the other. Try saving each actual UIImage to a file, e.g. [UIImagePNGRepresentation(screenShot) writeToFile:@"/tmp/image.png" atomically:NO]. Do it on the simulator and copy the image out of /tmp after each run.Selestina
Also, where is the text drawing done? Can you post that code?Selestina
F
5

I ended up fixing this by recursively setting the contentScaleFactor property of the parent view and its subviews to 2.0.

The UIImage was rendering at the correct resolution, but the layer wasn't when renderInContext was being called.

Felicafelicdad answered 5/11, 2012 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.