安卓(Android) 怎么从资源(Resource)加载opengl纹理

2019年10月19日12:20:08安卓(Android) 怎么从资源(Resource)加载opengl纹理已关闭评论 301 1395字阅读4分39秒

1.简介

安卓(Android) 怎么从资源(Resource)加载opengl纹理?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


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;
    }
}

 
继续阅读
编程十万个怎么办