Ios – OpenGL ES 2.0 GLKit with transparent background

glkitiosiphoneopengl-es

Is there a way to make the background of a GLKView transparent? I've tried the solution here but that isn't working for me.

*EDIT: I need help making it completely transparent. The background is mostly white and gray, but I just tested it with more vibrant colors, and sure enough you can vaguely see through to the background. Any ideas why it would be partly transparent but not fully with the following code?

Here's the code in my view controller:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.context = [[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2] autorelease];
    CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.view.layer;
    eaglLayer.opaque = NO;

    if (!self.context) {
       NSLog(@"Failed to create ES context");
    }

    GLKView *view = (GLKView *)self.view;
    view.context = self.context;

    view.backgroundColor = [UIColor clearColor];

    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

    [self setupGL];
}

- (void)setupGL
{
    [EAGLContext setCurrentContext:self.context];

    self.effect = [[[GLKBaseEffect alloc] init] autorelease];
    self.effect.light0.enabled = GL_FALSE;
    self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 0.0f);
    self.effect.light0.ambientColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 0.0f);

    glDisable(GL_DEPTH_TEST);

    glGenVertexArraysOES(1, &_vertexArray);
    glBindVertexArrayOES(_vertexArray);

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_DYNAMIC_DRAW);

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, VERTEX_POS_DATA_SIZE, GL_FLOAT, GL_FALSE, VERTEX_DATA_SIZE * sizeof(GLfloat), BUFFER_OFFSET(0));

    glEnableVertexAttribArray(GLKVertexAttribColor);
    glVertexAttribPointer(GLKVertexAttribColor, VERTEX_COLOR_DATA_SIZE, GL_FLOAT, GL_FLOAT, VERTEX_DATA_SIZE * sizeof(GLfloat), BUFFER_OFFSET(VERTEX_POS_DATA_SIZE * sizeof(GLfloat)));    

    glLineWidth(10.0);
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    if (!needsRedraw) return;
    needsRedraw = NO;

    glClearColor(0.65f, 0.65f, 0.65f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    [self.effect prepareToDraw];

    glDrawArrays(GL_LINE_STRIP, 0, vertexCount);    
}

I've tried setting the backgroundColor of the to [UIColor clearColor] and setting the eaglLayer to not be opaque. Heck, I even tried setting the backgroundColor of the eaglLayer to CGColorRef with 0 opacity.

Best Answer

Well, I didn't think this would matter because the alpha was already at 0.0f, but when I changed

glClearColor(0.65f, 0.65f, 0.65f, 0.0f);

to

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

it made the background perfectly transparent.

Thanks everyone for your suggestions and help!

Related Topic