Showing posts with label bitmap context. Show all posts
Showing posts with label bitmap context. Show all posts

Friday, September 14, 2012

Creating Bitmap Context for Retina and regular iOS devices

When it is a Retina display iOS device, the resolution is 4 times as a regular display.  How is a bitmap context created in this case that can make use of the higher resolution, while for a regular display, a regular bitmap context is used so that memory isn't wasted?

The answer is using the [[UIScreen mainScreen] scale], and create the bitmap context accordingly.  But will any drawing routine also take special care to draw on this bitmap context because now the pixels on x and y-axis have both doubled?

The solution is that we can just do a transform, and everything will be taken care of.  By doing this, any drawing routine will not need to tailor to any particular size.  Moving to a point at (300, 300) will be actually moving to pixel (600, 600), but the drawing can just use (300, 300) for both a regular and Retina device.  The solution is:

float scaleFactor = [[UIScreen mainScreen] scale];
CGSize size = CGSizeMake(768, 768);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, 
                           size.width * scaleFactor, size.height * scaleFactor, 
                           8, size.width * scaleFactor * 4, colorSpace, 
                           kCGImageAlphaPremultipliedFirst);
CGContextScaleCTM(context, scaleFactor, scaleFactor);

note that the last line, the CGContextScaleCTM is important.  It does the work of making (300, 300) to be the actually pixel (600, 600) on a Retina device.  The line that does the CGSizeMake(768, 768) is how big you'd like the bitmap context to be.  It works on a regular display and is automatically scaled up for a Retina display in the code above.





Followers