set OpenGL Render To Fit - Android android.opengl

Android examples for android.opengl:OpenGL

Description

set OpenGL Render To Fit

Demo Code

/*/*from  ww  w . ja  v  a2 s.c om*/
 * Copyright (C) 2010 The Android Open Source Project
 *
 * 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.
 */
import android.graphics.Bitmap;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class Main{
    private static final float[] POS_VERTICES = { -1.0f, -1.0f, 1.0f,
            -1.0f, -1.0f, 1.0f, 1.0f, 1.0f };
    private static final int FLOAT_SIZE_BYTES = 4;
    public static void setRenderToFit(RenderContext context, int srcWidth,
            int srcHeight, int dstWidth, int dstHeight) {
        context.posVertices = createVerticesBuffer(getFitVertices(srcWidth,
                srcHeight, dstWidth, dstHeight));
    }
    private static FloatBuffer createVerticesBuffer(float[] vertices) {
        if (vertices.length != 8) {
            throw new RuntimeException("Number of vertices should be four.");
        }

        FloatBuffer buffer = ByteBuffer
                .allocateDirect(vertices.length * FLOAT_SIZE_BYTES)
                .order(ByteOrder.nativeOrder()).asFloatBuffer();
        buffer.put(vertices).position(0);
        return buffer;
    }
    private static float[] getFitVertices(int srcWidth, int srcHeight,
            int dstWidth, int dstHeight) {
        float srcAspectRatio = ((float) srcWidth) / srcHeight;
        float dstAspectRatio = ((float) dstWidth) / dstHeight;
        float relativeAspectRatio = dstAspectRatio / srcAspectRatio;

        float[] vertices = new float[8];
        System.arraycopy(POS_VERTICES, 0, vertices, 0, vertices.length);
        if (relativeAspectRatio > 1.0f) {
            // Screen is wider than the camera, scale down X
            vertices[0] /= relativeAspectRatio;
            vertices[2] /= relativeAspectRatio;
            vertices[4] /= relativeAspectRatio;
            vertices[6] /= relativeAspectRatio;
        } else {
            vertices[1] *= relativeAspectRatio;
            vertices[3] *= relativeAspectRatio;
            vertices[5] *= relativeAspectRatio;
            vertices[7] *= relativeAspectRatio;
        }
        return vertices;
    }
}

Related Tutorials