如何捕获OpenGL视图作为UIImage?

ohh*_*hho 4 iphone opengl-es uiimage

当我尝试使用此方法将OpenGL视图转换为UIImage时,仅返回视图的背景,而不返回GLView内容.如何将OpenGL的上下文转换为UIImage?

Chr*_*oph 8

这取决于您使用的OpenGL视图.从iOS 5开始,您可以使用GLKit和相应的GLKView,这极大地简化了渲染UIImage的过程.

GLKView* v = (GLKView*) _previewViewController.view;
UIImage* thumbnail = [v snapshot];
Run Code Online (Sandbox Code Playgroud)

http://developer.apple.com/library/ios/#documentation/GLkit/Reference/GLKView_ClassReference/Reference/Reference.html


Jha*_*iya 6

使用以下代码转换您的opengl视图UIImage.

GLubyte *buffer = (GLubyte *) malloc(backingWidth * backingHeight * 4);
 GLubyte *buffer2 = (GLubyte *) malloc(backingWidth * backingHeight * 4);
 GLvoid *pixel_data = nil;
 glReadPixels(0, 0, backingWidth, backingHeight, GL_RGBA, GL_UNSIGNED_BYTE,
         (GLvoid *)buffer);
for (int y=0; y<backingHeight; y++) {
     for (int x=0; x<backingWidth*4; x++) {
         buffer2[y * 4 * backingWidth + x] =
     buffer[(backingHeight - y - 1) * backingWidth * 4 + x];
     }
 }
 CGDataProviderRef provider;
 provider = CGDataProviderCreateWithData(NULL, buffer2,
                                          backingWidth * backingHeight * 4,
                                          freeImageData);
 // set up for CGImage creation
 int bitsPerComponent = 8;
 int bitsPerPixel = 32;
 int bytesPerRow = 4 * backingWidth;
 CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
 CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
 // Use this to retain alpha
 //CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
 CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
 CGImageRef imageRef = CGImageCreate(backingWidth, backingHeight,
                                 bitsPerComponent, bitsPerPixel,
                                 bytesPerRow, colorSpaceRef,
                                 bitmapInfo, provider,
                                 NULL, NO,
                                 renderingIntent);
 // this contains our final image.
 UIImage *newUIImage = [UIImage imageWithCGImage:imageRef];
Run Code Online (Sandbox Code Playgroud)

取自