get EAGLview screenshot with transparency in landscape mode

this is NOT mine actually. the original source can be found at the end of this post. i post here just for helping people who may need it. so they don’t need to spend whole day for “googling” this like i did. 😀

the key to get the transparency is this line:

[code language=”cpp”]
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
[/code]

now, this is the complete method. NOTE: this is for landscape mode (480 x 320), if you want in portrait, simply modify the size.

[code language=”cpp” wraplines=”false”]
– (UIImage*) getGLScreenshot {
NSInteger myDataLength = 480 * 320 * 4;

// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, 480, 320, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

// gl renders "upside down" so swap top to bottom into new array.
// there’s gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y <320; y++)
{
for(int x = 0; x < 480* 4; x++)
{
buffer2[(319 – y) * 480 * 4 + x] = buffer[y * 4 * 480 + x];
}
}

// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
buffer2, myDataLength, NULL);

// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * 480;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();

/***************** to handle the transparency/alpha ******************/
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
//CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
/*********************************************************************/

CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

// make the cgimage
CGImageRef imageRef = CGImageCreate(480, 320, bitsPerComponent,
bitsPerPixel, bytesPerRow, colorSpaceRef,
bitmapInfo, provider, NULL, NO, renderingIntent);

// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
return myImage;
}

[/code]

Source: www.iphonedevsdk.com