public
Last active

  • Download Gist
AlphaBlending.md
Markdown

Alpha Masking Without Shaders

Shaders are often more efficient, but for simple purposes this may do the trick. It also means it supports GLES10.

The three textures can be downloaded here.

BlendTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
 
public class BlendTest implements ApplicationListener {
 
public static void main(String[] args) {
LwjglApplication app = new LwjglApplication(new BlendTest(), "Test", 480, 320, true);
}
OrthographicCamera cam;
SpriteBatch batch;
Texture bg, sprite, alphaMask;
 
@Override
public void create () {
cam = new OrthographicCamera();
batch = new SpriteBatch();
bg = new Texture("data/badlogic.jpg");
sprite = new Texture("data/grass.png");
alphaMask = new Texture("data/mask.png");
alphaMask.setFilter(TextureFilter.Linear, TextureFilter.Linear);
}
 
@Override
public void resize (int width, int height) {
cam.setToOrtho(false, width, height);
batch.setProjectionMatrix(cam.combined);
}
 
@Override
public void render () {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
int w = Gdx.graphics.getWidth();
int h = Gdx.graphics.getHeight();
batch.begin();
//tell SpriteBatch not to apply any blend modes...
//regular blending mode
batch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
//draw background with regular blending
batch.draw(bg, 0, 0, w, h);
batch.flush();
 
//the sprite we want the circle mask applied to
int x = 25;
int y = 50;
int spriteWidth = 200;
int spriteHeight = 200;
//now draw the alpha into the frame buffer
Gdx.gl.glColorMask(false, false, false, true);
batch.setBlendFunction(GL10.GL_ONE, GL10.GL_ZERO);
batch.draw(alphaMask, x, y, spriteWidth, spriteHeight);
batch.flush();
//now that the buffer has our alpha, we simply draw the sprite with the mask applied
Gdx.gl.glColorMask(true, true, true, true);
batch.setBlendFunction(GL10.GL_DST_ALPHA, GL10.GL_ONE_MINUS_DST_ALPHA);
batch.draw(sprite, x, y, spriteWidth, spriteHeight);
batch.flush();
batch.end();
}
 
@Override
public void pause () {
}
 
@Override
public void resume () {
}
 
@Override
public void dispose () {
batch.dispose();
alphaMask.dispose();
sprite.dispose();
bg.dispose();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.