在CGL中拍摄内容的快照?

时间:2011-08-29 14:41:01

标签: macos opengl core-graphics cglayer

我想用Core OpenGL上下文创建一个图像。

我使用了以下代码,但它创建了一个黑色图像。所以我想我不能在那里使用glReadPixles?还有其他建议吗?

int myDataLength = 480 * 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();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

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

//PRINT image... Its black!!!!!!

CGDataProviderRelease(provider);
free(buffer);
free(buffer2);

1 个答案:

答案 0 :(得分:1)

在进行glReadPixels呼叫之前,您必须

  • 设置正确的包装(参见 glPixelStorei 参考页面)
  • 选择正确的缓冲区以使用 glReadBuffer 进行读取(交换前面,交换前返回,我建议交换并从前面读取)