Как нарисовать изображение в OpenGL Android - PullRequest
1 голос
/ 14 октября 2011

Мне нужно нарисовать растровое изображение на моих живых обоях, используя этот код, но изображение не будет загружено с исключением из-за нулевого указателя.

public class Square {

    private FloatBuffer vertexBuffer; // buffer holding the vertices
    private float vertices[] = { -1.0f, -1.0f, 0.0f, // V1 - bottom left
            -1.0f, 1.0f, 0.0f, // V2 - top left
            1.0f, -1.0f, 0.0f, // V3 - bottom right
            1.0f, 1.0f, 0.0f // V4 - top right
    };

    private FloatBuffer textureBuffer; // buffer holding the texture coordinates
    private float texture[] = {
    // Mapping coordinates for the vertices
            0.0f, 1.0f, // top left (V2)
            0.0f, 0.0f, // bottom left (V1)
            1.0f, 1.0f, // top right (V4)
            1.0f, 0.0f // bottom right (V3)
    };

    /** The texture pointer */
    int[] textures = new int[1];

    public Square() {

        // a float has 4 bytes so we allocate for each coordinate 4 bytes
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
        byteBuffer.order(ByteOrder.nativeOrder());

        // allocates the memory from the byte buffer
        vertexBuffer = byteBuffer.asFloatBuffer();

        // fill the vertexBuffer with the vertices
        vertexBuffer.put(vertices);

        // set the cursor position to the beginning of the buffer
        vertexBuffer.position(0);

        byteBuffer = ByteBuffer.allocateDirect(texture.length * 4);
        byteBuffer.order(ByteOrder.nativeOrder());
        textureBuffer = byteBuffer.asFloatBuffer();
        textureBuffer.put(texture);
        textureBuffer.position(0);
    }

    /**
     * Load the texture for the square
     * 
     * @param gl
     * @param context
     */
    public void loadGLTexture(GL10 gl, Context context) {
        System.out.println("loaded");
        // // loading texture
         Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
         R.drawable.nehe);
//here is the problem when ever i command bitmap it will be working .with out command its //showing null pointer exception   
        // generate one texture pointer
        gl.glGenTextures(1, textures, 0);
        // ...and bind it to our array
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

        // create nearest filtered texture
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
                GL10.GL_NEAREST);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
                GL10.GL_LINEAR);

        // Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
                GL10.GL_REPEAT);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
                GL10.GL_REPEAT);

        // Use Android GLUtils to specify a two-dimensional texture image from
        // our bitmap
         GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
        // //
        // // // Clean up
         bitmap.recycle();
    }

    /** The draw method for the square with the GL context */
    public void draw(GL10 gl) {
        // System.out.println("draw");
        // bind the previously generated texture
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

        // Point to our buffers
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        // Set the face rotation
        gl.glFrontFace(GL10.GL_CW);

        // Point to our vertex buffer
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

        // Draw the vertices as triangle strip
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);

        // Disable the client state before leaving
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    }
}

это мой вывод logcat

10-14 11:43:43.118: WARN/dalvikvm(3050): threadid=8: thread exiting with uncaught exception (group=0x4001d868)
10-14 11:43:43.118: ERROR/AndroidRuntime(3050): FATAL EXCEPTION: GLThread 9
10-14 11:43:43.118: ERROR/AndroidRuntime(3050): java.lang.NullPointerException
10-14 11:43:43.118: ERROR/AndroidRuntime(3050):     at frankandrobot.glwallpapervideodemo.com.Square.loadGLTexture(Square.java:73)
10-14 11:43:43.118: ERROR/AndroidRuntime(3050):     at frankandrobot.glwallpapervideodemo.com.VideoRenderer.onSurfaceCreated(VideoRenderer.java:77)
10-14 11:43:43.118: ERROR/AndroidRuntime(3050):     at net.rbgrn.android.glwallpaperservice.GLThread.guardedRun(GLWallpaperService.java:664)
10-14 11:43:43.118: ERROR/AndroidRuntime(3050):     at net.rbgrn.android.glwallpaperservice.GLThread.run(GLWallpaperService.java:538)
10-14 11:43:56.398: WARN/Email(1452): Exception detected: Read error: I/O error during system call, Connection reset by peer
10-14 11:43:56.398: WARN/Email(1452): Last network activities:
10-14 11:43:56.398: WARN/Email(1452): * OK Gimap ready for requests from 115.111.177.222 g2if3342858pbc.293
10-14 11:43:56.398: WARN/Email(1452): 1 CAPABILITY
10-14 11:43:56.398: WARN/Email(1452): * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH
10-14 11:43:56.398: WARN/Email(1452): 1 OK Thats all she wrote! g2if3342858pbc.293
10-14 11:43:56.398: WARN/Email(1452): 2 ID ("name" "com.android.email" "os" "android" "os-version" "2.2; FRF91" "vendor" "nvidia" "x-android-device-model" "INB-10/n" "AGUID" "+TIbwSeLDHum85UXux4T+QJD51g=")

нужна помощь, чтобы сделать это. Пожалуйста, наведите меня на простой способ, я новичок в Android и OpenGL ....

Ответы [ 3 ]

1 голос
/ 13 января 2012

Попробуйте переместить nehe.png (или jpg или любой другой) вместо res / raw, а затем используйте следующее:

InputStream inStream = context.getResources().openRawResource(R.raw.nehe);
Bitmap bitmap = BitmapFactory.decodeStream(inStream);

, очевидно, заменив:

Bitmap bitmap =BitmapFactory.decodeResource (context.getResources (), R.drawable.nehe);

0 голосов
/ 25 сентября 2013

Была такая же проблема, и это было в классе рендеринга, а не в loadGLTexture. Произошла ошибка, поскольку «Контекст контекста» неправильно определен / вызван везде в живых обоях. Убедитесь, что у класса рендерера есть контекст, например:

...
Private Square square;
Private Context context;

для класса рендерера также нужно добавить в метод рендерера что-то вроде:

public Myrenderer(Context context){

   this.context=context;
   square = new Square();
}

и для сервиса обоев что-то вроде:

renderer = new render(getBaseContext());

Вы также можете определить метод setContext для определения контекста из сервиса обоев:

renderer = new MyRenderer();
renderer.setContext(getBaseContext());
setRenderer(renderer);

рабочий код: https://github.com/GLWallpaperService/GLWallpaperService/pull/7

0 голосов
/ 14 октября 2011

Можете ли вы сказать нам, какая строка имеет номер 73?

Полагаю, вы не инициализировали textures переменную (например):

 int[] textures = new int[1];
...