Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;

import android.opengl.GLUtils;

import java.util.HashMap;
import java.util.Map;

public class Main {
    private static final Map<Integer, Integer> cachedTextureHandles = new HashMap<>();

    /**
     * Loads the texture with the given id.
     *
     * @param context    the application's context
     * @param resourceId the id of the texture
     * @return the texture handle
     */
    public static int loadTexture(final Context context, final int resourceId) {
        final int[] textureHandle = new int[1];

        if (!cachedTextureHandles.containsKey(resourceId)) {
            GLES20.glGenTextures(1, textureHandle, 0);

            if (textureHandle[0] != 0) {
                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inScaled = false; // Pre scaling off

                final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);

                GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
                GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
                GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);

                GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

                bitmap.recycle();

                if (textureHandle[0] == 0) {
                    throw new RuntimeException("Error loading texture.");
                }

                cachedTextureHandles.put(resourceId, textureHandle[0]);
            }
        }
        return cachedTextureHandles.get(resourceId);
    }
}