Pergunta

I have some .png files that I'm using as textures for my 2d game quad sprites.

Some of these already have partially transparent pixels in them and I need to be able to display them correctly and fade them in/out.

Initially, I was drawing them with the following blending mode:

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

This works fine for the textures that are solid to begin with and I can use any value between 1.0f and 0.0f to introduce transparency. So far so good, but when I try to use png's that already have transparency in them, they won't display correctly (They are too dark and have a dark outline).

I did a lot of research and I found out that I needed to change my blending mode for these types of textures, as the above one wouldn't work properly, so this is now what I have (including my shader)......

Fragment shader

String strFShader =
"precision mediump float;" +
"varying vec2 v_texCoords;" +
"uniform sampler2D u_baseMap;" +
"void main()" +
"{" +
"gl_FragColor = texture2D(u_baseMap, v_texCoords);" +
"gl_FragColor.a *= "+1.0f+";"+  //** Where 1.0f is the amount to blend, with 0.0f being completely transparent and 1.0f being as per the original png file.
 "}";

Code

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

GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

GLES20.glDisable(GLES20.GL_BLEND);

if I draw semi-transparent textures using this with a value of 1.0f in the shader (as above) it draws great. However, if I then try to fade it out, some colours seem to fade out and some don't so when it's at 0.0f I'm just left with an odd colour version of the original texture.

Would be grateful if someone could show me how to render these types of textures correctly.

Thanks

Foi útil?

Solução 2

I didn't need to convert the images to non-premultiplied images in the end, I simply kept them in that format and changed the line in my shader to:

"gl_FragColor *= "+op+";"+

And used....

GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

Works perfectly.

Outras dicas

If they are too dark and have dark outlines, this seems to be caused by color channel being premultiplied by alpha channel. In this case, in parts where texture is very transparent colors are dim. Let's say, if alpha of pixel is 0.9 then premultiplied RGB colors will be 90% dimmer than they actually are.

In order to load PNG images without RGB channels being premultiplied by alpha we use 3rd party PNGDecoder and then load texture with glTexImage2D(). You can get PNGDecoder library to decode PNG from here: http://twl.l33tlabs.org/#downloads

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top