Search code examples
iosopengl-esglkitalphablending

Applying mask for transparent image in OpenGL


I am trying to apply mask in OpenGl to image which has transparency.
My current code looks like this:

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
  glClearColor(1, 0, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT);
  glEnable(GL_BLEND);

  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  [self.bgSprite render];

  glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
  [self.maskSprite render];

  glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
  [self.contentSprite render];
}

So, first of all I am drawing my background sprite, then cutting a hole into it with my mask, and then drawing masked image inside that hole. But this approach is not what I need, because I want to see my background texture in places, where my content image is transparent, but now I am seeing there white color.
Before that I worked with android, and there I was able to use Pointer Duff modes. First step was drawing mask with SOURCE mode, then content image with SOURCE_IN, and then background with DESTINATION_OVER. But I can't find it in OpenGL.


Solution

  • I got it.
    Here are he steps

    glClearColor(1, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
    glEnable(GL_BLEND);
    
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    [self.maskSprite render];
    
    glBlendFunc(GL_DST_ALPHA, GL_ZERO);
    [self.contentSprite render];
    
    glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
    [self.bgSprite render];