OpenGL ES 2.0 PNG alpha channel

大城市里の小女人 提交于 2019-12-04 03:26:20

Change

 for ( int y = 0; y < bitmap.getHeight(); y++ )
    for ( int x = 0; x < bitmap.getWidth(); x++ )
    {
        int pixel = bitmap.getPixel(x, y);
        buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
        buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
        buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
    }

into

 for ( int y = 0; y < bitmap.getHeight(); y++ )
    for ( int x = 0; x < bitmap.getWidth(); x++ )
    {
        int pixel = bitmap.getPixel(x, y);
        buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
        buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
        buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
        buffer[(y * bitmap.getWidth() + x) * 4 + 3] = (byte)((pixel >> 24) & 0xFF);
    }

to include the alpha information then simply add

GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
GLES20.glEnable(GLES20.GL_BLEND); 

right before you draw the texture. Remember to disable GL_BLEND once you are done.

You most likely want to use glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) as the blending function and you have to make sure to also write the alpha value of the texture to the gl_FragColor fragment shader output variable.

For all that to work your uploaded texture data has to contain an alpha value and you must have used a texture format that supports an alpha channel (RGBA, RGBA8 etc.).

You could verify this by simply routing the alpha value to the RGB color components and inspecting the image that you get.

EDIT:

In your image loading code you forget to copy over the alpha channel! Try the suggestion that davebytes gives.

your initial shader is fine. alpha is inherent in color ops, it just may not be applied depending on blend/mode/etc.

given that your texture comes out black if you do fragcolor = base.aaa, that implies your texture data is 'bad'.

looking at your texture load, yeah, it's wrong. you never copy over the alpha, just the rgb. assuming java clears the byte array to 0s, all alpha will be zero, that would get you your black box, that would cause the image to 'vanish' when you enable alpha blending.

To simplify your life, instead of all the hand copying and stuff, you can simply load the bitmap normally and use the GLUtils helper to upload instead of directly using glTexImage2d:

  bitmap = BitmapFactory.decodeStream(is);  
  GLES20.glGenTextures ( 1, textureId, 0 );
  GLES20.glBindTexture ( GLES20.GL_TEXTURE_2D, textureId[0] );
  GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

Something like that. Then enable blending, use src+invsrc blend mode if not premultiplied, and render, you should get the result desired.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!