在Android上OpenGl 实现逐帧动画的播放效果的Java实现代码
时间: 2024-02-20 13:59:11 浏览: 237
android opengl-es 2.0 java 实现绘制三角形
以下是一个简单的Java代码示例,演示如何在Android上使用OpenGL实现逐帧动画的播放效果:
```java
public class MyGLRenderer implements GLSurfaceView.Renderer {
private Context mContext;
private int[] mTextures;
private int mCurrentFrame = 0;
private int mFrameCount;
private int mFrameWidth;
private int mFrameHeight;
public MyGLRenderer(Context context, int frameCount, int frameWidth, int frameHeight) {
mContext = context;
mFrameCount = frameCount;
mFrameWidth = frameWidth;
mFrameHeight = frameHeight;
mTextures = new int[frameCount];
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// 初始化OpenGL ES
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
// 加载动画帧图像资源
for (int i = 0; i < mFrameCount; i++) {
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.frame_1 + i);
gl.glGenTextures(1, mTextures, i);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[i]);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
// 设置视口大小
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0, width, 0, height);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
@Override
public void onDrawFrame(GL10 gl) {
// 绘制纹理
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[mCurrentFrame]);
float ratio = (float) mFrameWidth / mFrameHeight;
gl.glPushMatrix();
gl.glTranslatef((gl.glGetParameter(GL10.GL_VIEWPORT, 0) - mFrameWidth) / 2, (gl.glGetParameter(GL10.GL_VIEWPORT, 1) - mFrameHeight) / 2, 0);
gl.glScalef(Math.min(gl.glGetParameter(GL10.GL_VIEWPORT, 2) / (float) mFrameWidth, gl.glGetParameter(GL10.GL_VIEWPORT, 3) / (float) mFrameHeight), Math.min(gl.glGetParameter(GL10.GL_VIEWPORT, 2) / (float) mFrameWidth, gl.glGetParameter(GL10.GL_VIEWPORT, 3) / (float) mFrameHeight) * ratio, 1);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
float vertices[] = {0, 0, 0, mFrameHeight, mFrameWidth, mFrameHeight, mFrameWidth, 0};
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, FloatBuffer.wrap(vertices));
float texCoords[] = {0, 0, 0, 1, 1, 1, 1, 0};
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, FloatBuffer.wrap(texCoords));
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, 4);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glPopMatrix();
// 更新当前显示的纹理
mCurrentFrame = (mCurrentFrame + 1) % mFrameCount;
}
}
```
你可以将以上代码添加到你的Android项目中,并根据实际需求进行调整和优化。
阅读全文