Hey guys,
Was having problems with this exact same issue.
This thread got me started down the road to the solution.
So I thought I'd share what I learned.
I didn't actually work out myself, but put it together from various forum threads and this little
blog post in which a post by a guy called gamekozo in the comment section gave me the final piece of the puzzle.
This is the piece of code that takes the contents of the drawing view / painting view / EAGLView / GLView (whatever you want to call it), renders it.
Then turns it into a UIImage and passes it back to whereever it came from.
Code:
- (UIImage *) glToUIImage {
NSInteger myDataLength = 320 * 480 * 4;
// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, 320, 480, 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 <480; y++)
{
for(int x = 0; x <320 * 4; x++)
{
buffer2[(479 - y) * 320 * 4 + x] = buffer[y * 4 * 320 + 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 * 320;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
//xxxxxx This is the line of code that I found in multiple solutions throughout the web but doesn't deal with the transparency
// CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
//xxxxxx
//*******This is the code I used to handle the tranparency!!!
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
//*******
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
// make the cgimage
CGImageRef imageRef = CGImageCreate(320, 480, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
return myImage;
}
The vital piece of code for being able to save the transparency/alpha properties of the GLView is the line:
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
You can use code like the following to save the image created from the GLView in the code above.
Below I create an UIImage which I then put the image rendered into.
Then save it to the Camera Roll / Photo Album
Code:
UIImage *viewImage = [self glToUIImage];
//code to write the image to the Photo Album
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
You can put the image into an ImageView over a background and then save the whole thing etc.
Hope that helps people and saves them a day of searching.
~Anthony