简体   繁体   中英

Render contents of UIView as an OpenGL ES texture but only black turns out

I'm learning OpenGL ES with the tutorial on raywenderlich.com http://www.raywenderlich.com/4404/opengl-es-2-0-for-iphone-tutorial-part-2-textures

When I get started to tweak the example project to grasp a UIView's content as the texture to get rendered, it's only black screen turns out just like: 黑色视图是OpenGL ES视图

The black view is the OpenGL ES view.

I used the code posted by Tommy in this post: Render contents of UIView as an OpenGL texture , and here is my version:

- (GLuint)createTexture:(UIView *)view
{
    size_t width = CGRectGetWidth(view.layer.bounds) * [UIScreen mainScreen].scale;
    size_t height = CGRectGetHeight(view.layer.bounds) * [UIScreen mainScreen].scale;

    GLubyte * texturePixelBuffer = (GLubyte *) calloc(width * height * 4,
                                   sizeof(GLubyte));

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(texturePixelBuffer,
                                                 width, height, 8, width*4, colorSpace, 
                                                 kCGImageAlphaPremultipliedLast | 
                                                 kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    [view.layer renderInContext:context];

    CGContextRelease(context);

    GLuint texName;
    glGenTextures(1, &texName);
    glBindTexture(GL_TEXTURE_2D, texName);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, 
                 GL_UNSIGNED_BYTE, texturePixelBuffer);

    free(texturePixelBuffer);
    return texName;
}

According to Open GL ES 2.0 Specification, texture can either be the power of two or not. But you must use

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

to enable non-power-of-two texture support.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM