什么时候可以使用glReadPixels?

时间:2012-07-10 12:06:26

标签: iphone xcode ipad glreadpixels

我想知道GLReadPixels功能的使用./ 它是如何读取像素的? 是在glreadFunction中提供的边界内的主屏幕上读取GLKView像素或UIView像素或任何内容。 或者它只能在我们使用GLKView ??

时使用

请澄清我的疑问。

2 个答案:

答案 0 :(得分:0)

它从当前的OpenGL(ES)帧缓冲区读取像素。它不能用于从UIView读取像素,但它可用于从GLKView读取,因为它由帧缓冲提供支持(但是,它只能在其活动帧缓冲区时读取其数据) ,它很可能是在绘图时)。但是,如果您想要的所有内容都是GLKView的屏幕截图,则可以使用其内置的snapshot方法获取包含其内容的UIImage

答案 1 :(得分:0)

您可以使用glreadPixels读取背景屏幕。这是要做的代码。

- (UIImage*) getGLScreenshot {
    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();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    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;
}

- (void)saveGLScreenshotToPhotosAlbum {
    UIImageWriteToSavedPhotosAlbum([self getGLScreenshot], nil, nil, nil);
}
相关问题