Skip to content

Instantly share code, notes, and snippets.

Created Mar 4, 2021
What would you like to do?
fun Resources.loadBitmapForTexture(@DrawableRes drawableRes: Int): Bitmap {
val options = BitmapFactory.Options()
options.inScaled = false // true by default. false if we need scalable image
// load from resources
return BitmapFactory.decodeResource(this, drawableRes, options)
* Load texture from Bitmap and write it to the video memory
* @needToRecycle - do we need to recycle current Bitmap when we write it GPI?
fun Bitmap.toGlTexture(needToRecycle: Boolean = true, textureSlot: Int = GLES30.GL_TEXTURE0): Int {
// init textures
val textureIds = IntArray(1)
GLES30.glGenTextures(1, textureIds, 0) // generate ID for texture
if (textureIds[0] == 0) {
throw java.lang.RuntimeException("It's not possible to generate ID for texture")
GLES30.glActiveTexture(textureSlot) // activate slot #0 for texture
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureIds[0]) // bind texture by ID with active slot
// texture filters
// write bitmap to GPU
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, this, 0)
// we don't need this bitmap anymore
if (needToRecycle) {
// unbind texture from slot
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return textureIds[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment