load OpenGL Texture from resource - Android App

Android examples for App:Resource

Description

load OpenGL Texture from resource

Demo Code

/**//from ww  w. j a va 2s  .  c o m
 * Copyright 2015 Michael Leahy / TyphonRT, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.opengl.GLUtils;

import static android.opengl.GLES20.*;

public class Main {
    private static final ThreadLocal<int[]> s_LOAD_TEXTURE_ID = new ThreadLocal<int[]>();

    public static int loadTexture(Resources resources, int resource,
            boolean flip) {
        int[] textures = s_LOAD_TEXTURE_ID.get();
        if (textures == null) {
            textures = new int[1];
            s_LOAD_TEXTURE_ID.set(textures);
        }

        glActiveTexture(GL_TEXTURE0);
        glGenTextures(1, textures, 0);

        int texture = textures[0];
        glBindTexture(GL_TEXTURE_2D, texture);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        Bitmap bitmap = BitmapFactory.decodeResource(resources, resource);

        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();

        if (flip) {
            Matrix matrix = new Matrix();
            matrix.setScale(1, -1);
            matrix.postTranslate(0, height);
            Bitmap flipBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
                    height, matrix, true);

            bitmap.recycle();
            bitmap = flipBitmap;
        }

        GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap,
                GL_UNSIGNED_BYTE, 0);

        bitmap.recycle();

        glBindTexture(GL_TEXTURE_2D, 0);

        return texture;
    }
}

Related Tutorials