Question

I'm trying to blend 2 images together in the following way:

Image 1 should be drawn as the base image. Image 2 should be drawn overtop of image 1. Anywhere image 2 is non-transparent, it should replace the contents of image 1 (not blend, but overwrite what is there). Wherever image 2 is transparent, image 1 should show through. I've tried to do this with the following code, but I'm obviously doing something incorrectly with the blending.

            gl.glEnable(GL.GL_BLEND);
            if (iconTexture1 != null)
            {
                gl.glEnable(GL.GL_TEXTURE_2D);
                iconTexture1.bind();
                double red = (double) fillColor.getRed() / 255.0;
                double green = (double) fillColor.getGreen() / 255.0;
                double blue = (double) fillColor.getBlue() / 255.0;
                gl.glColor4d(red, green, blue, this.getOpacity());
                gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
                TextureCoords texCoords = iconTexture1.getImageTexCoords();
                gl.glScaled(width, height, 1d);
                dc.drawUnitQuad(texCoords);
            }
            if (iconTexture2 != null)
            {
                gl.glEnable(GL.GL_TEXTURE_2D);
                iconTexture2.bind();
                // image2 is all white, so color it here
                gl.glColor4d(1d, 0d, 0d, 1d);

                // TODO: What blend function should I be using here to allow image 2 to overwrite what is already there?

                TextureCoords texCoords = iconTexture2.getImageTexCoords();
                gl.glScaled(width, height, 1d);
                dc.drawUnitQuad(texCoords);
            }

Any help to make this work correctly would be appreciated. Thanks.

Jeff

Was it helpful?

Solution

There are a few things that might be issues:

  1. You shouldn't turn the blending function on until after you have drawn image 1. Doing so before will blend image 1 with whatever was there already.
  2. I'm not a big texture user, but I think using texture will override the color of the quad, including any alpha you have specified; so unless the texture has alpha you won't get any blending.
  3. If you have z-buffering enabled, then maybe image 2 is behind image1; that would obscure it, even if image 2 is transparent. Special methods have to be used to draw transparent 3d.

A good way of working with OpenGL things that don't seem to work is to remove all the complexity, and then add it back bit by bit. The texture is your most complex part - leave that 'til last.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top