Search code examples
iphoneiosipadcore-graphicscgimage

How to save image larger than device resolution in iPhone?


My question is related to this link

I would like to know how we can save images larger than device resolution using CGBitmapContextCreate .

Any sample code for guidance will be much appreciated.

thanks!


Solution

  • Don't use CGBitmapContextCreate, use UIGraphicsBeginImageContextWithOptions, it's much easier. Use it like this:

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 1.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //do your drawing
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEdnImageContext();
    
    //your resultant UIImage is now stored in image variable
    

    The three parameters to UIGraphicsBeginImageContext are:

    1. The size of the image - this can be anything you want

    2. Whether the image has transparency or not

    3. The scale of pixels in the image. 0.0 is the default, so on an iPhone 3GS it will be 1.0 and on an iPhone 4 with a retina display it will be 2.0. You can pass in any scale you want though, so if you pass in 5.0, each pixel unit in your image will actually be 5x5 pixels in the bitmap, just like 1 pixel on a Retina display is really 2x2 pixels on screen.

    Edit: it turns out that the question of whether UIGraphicsBeginImageContext() is thread-safe seems to be a bit controversial. If you do need to do this concurrently on a background thread, there is an alternative (rather more complex approach) using CGBitMapContextCreate() here: UIGraphicsBeginImageContext vs CGBitmapContextCreate