Pinwheeler
Pinwheeler

Reputation: 1111

Creating a higher-resolution PNG image programmatically

So I have some copypasta way to create a PNG file and it's working splendidly, however, when going to print this PNG it appears kind of "blurry" like a low resolution image. Is there any way to create the PNG with a higher pixel depth?

Here's my current code:

- (UIImage*) renderScrollViewToImage
{
    UIImage* image = nil;

    UIGraphicsBeginImageContext(self.scrollView.contentSize);
    {
        CGPoint savedContentOffset = self.scrollView.contentOffset;
        CGRect savedFrame = self.scrollView.frame;

        self.scrollView.contentOffset = CGPointZero;
        self.scrollView.frame = CGRectMake(0, 0, _scrollView.contentSize.width, _scrollView.contentSize.height);

        [self.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();

        _scrollView.contentOffset = savedContentOffset;
        _scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();

    if (image != nil) {
        return image;
    }
    return nil;
}

Upvotes: 1

Views: 1116

Answers (1)

Or Arbel
Or Arbel

Reputation: 2975

try replacing:

UIGraphicsBeginImageContext(self.scrollView.contentSize);

with

UIGraphicsBeginImageContextWithOptions(self.scrollView.contentSize, NO, 0.0);

which will take into account retina scaling. docs:

UIGraphicsBeginImageContextWithOptions
Creates a bitmap-based graphics context with the specified options.

void UIGraphicsBeginImageContextWithOptions(
   CGSize size,
   BOOL opaque,
   CGFloat scale
);
Parameters
size
The size (measured in points) of the new bitmap context. This represents the size of the image returned by the UIGraphicsGetImageFromCurrentImageContext function. To get the size of the bitmap in pixels, you must multiply the width and height values by the value in the scale parameter.
opaque
A Boolean flag indicating whether the bitmap is opaque. If you know the bitmap is fully opaque, specify YES to ignore the alpha channel and optimize the bitmap’s storage. Specifying NO means that the bitmap must include an alpha channel to handle any partially transparent pixels.
scale
The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

Upvotes: 1

Related Questions