LibGDX: Masking using Blending Function 🎭

Masking using Blending Function

Photo by Edilson Borges on Unsplash

The first step is common to all examples

  1. Set up a standard project with this guide: https://veldan1202.medium.com/libgdx-%D1%82%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE-%D0%B4%D0%BB%D1%8F-android-4858e26734cf
  2. Android:
class LibGDXGame : ApplicationAdapter(), AdvancedInputProcessor {

private val batch by lazy { SpriteBatch() }
private val renderer by lazy { ShapeRenderer() }

override fun create() {
Gdx.input.inputProcessor = this
}

override fun render() {
ScreenUtils.clear(Color.DARK_GRAY)
}
}



fun Batch.begend(block: Batch.() -> Unit = {}) {
begin()
block()
end()
}

fun ShapeRenderer.begend(type: ShapeRenderer.ShapeType, block: ShapeRenderer.() -> Unit = {}) {
begin(type)
block()
end()
}



interface AdvancedInputProcessor: InputProcessor {
override fun keyDown(keycode: Int): Boolean {
return false
}

override fun keyUp(keycode: Int): Boolean {
return false
}

override fun keyTyped(character: Char): Boolean {
return false
}

override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
return false
}

override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
return false
}

override fun touchDragged(screenX: Int, screenY: Int, pointer: Int): Boolean {
return false
}

override fun mouseMoved(screenX: Int, screenY: Int): Boolean {
return false
}

override fun scrolled(amountX: Float, amountY: Float): Boolean {
return false
}
}
  1. Put the image in the resources folder:
private fun Batch.drawMask() {
Gdx.gl.glColorMask(false, false, false, true)

setBlendFunction(GL20.GL_ONE, GL20.GL_ZERO)
draw(img, maskX, maskY)
}
private fun Batch.drawMasked() {
setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_ALPHA)
draw(img, imgX, imgY)
flush()

Gdx.gl.glColorMask(true, true, true, true)
setBlendFunction(GL20.GL_DST_ALPHA, GL20.GL_ONE_MINUS_DST_ALPHA)
draw(img, imgX, imgY)
flush()

setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
}
private fun Batch.drawMask() {
Gdx.gl.glColorMask(false, false, false, true)

// setBlendFunction(GL20.GL_ONE, GL20.GL_ZERO)
setBlendFunction(GL20.GL_ZERO, GL20.GL_ONE_MINUS_SRC_ALPHA)
draw(img, maskX, maskY)
}
  1. Put the image in the resources folder

--

--

LibGDX | Android | Developer | DragonBones | Enthusiast.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store