1. 工程的建立
eclipse --> 新建一项目 com.example.gldemo
SDK 都选API 19: android 4.4 (KitKat)
2. 代码分析
MainActivity.java
-
package com.example.gldemo;
-
-
import android.app.Activity;
-
import android.os.Bundle;
-
import android.view.Menu;
-
import android.view.MenuItem;
-
-
public class MainActivity extends Activity {
-
private VortexView _vortexView;
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
_vortexView = new VortexView(this); -->使用opengl的view
-
setContentView(_vortexView);
-
//setContentView(R.layout.activity_main);
-
}
-
-
@Override
-
public boolean onCreateOptionsMenu(Menu menu) {
-
// Inflate the menu; this adds items to the action bar if it is present.
-
getMenuInflater().inflate(R.menu.main, menu);
-
return true;
-
}
-
-
@Override
-
public boolean onOptionsItemSelected(MenuItem item) {
-
// Handle action bar item clicks here. The action bar will
-
// automatically handle clicks on the Home/Up button, so long
-
// as you specify a parent activity in AndroidManifest.xml.
-
int id = item.getItemId();
-
if (id == R.id.action_settings) {
-
return true;
-
}
-
return super.onOptionsItemSelected(item);
-
}
- }
-
package com.example.gldemo;
-
-
import android.content.Context;
-
import android.opengl.GLSurfaceView;
-
import android.view.MotionEvent;
-
-
public class VortexView extends GLSurfaceView{ -->VortexView继承了GLSurfaceView
-
private static final String LOG_TAG="VortexView";
-
private VortexRenderer _renderer;
-
public VortexView (Context context){
-
super(context);
-
_renderer = new VortexRenderer(); -->使用opengl的view
-
setRenderer(_renderer); -->Renderer负责OpenGL call来render一个帧
-
}
-
-
public boolean onTouchEvent(final MotionEvent event){
-
queueEvent(new Runnable(){
-
public void run(){
-
_renderer.setColor(event.getX()/getWidth(),
-
event.getY()/getHeight(), 1.0f);
-
}
-
});
-
return true;
-
}
- }
-
package com.example.gldemo;
-
-
import javax.microedition.khronos.egl.EGLConfig;
-
import javax.microedition.khronos.opengles.GL10;
-
-
import android.opengl.GLSurfaceView;
-
-
public class VortexRenderer implements GLSurfaceView.Renderer {
-
private static final String LOG_TAG="VortexRenderer";
-
private float _red = 0.9f;
-
private float _green = 0.9f;
- private float _blue = 0.9f;
-
-
@Override
-
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
-
// TODO Auto-generated method stub
-
-
}
-
-
@Override
-
public void onSurfaceChanged(GL10 gl, int w, int h){
-
gl.glViewport(0, 0, w, h);
-
}
-
-
@Override
-
public void onDrawFrame(GL10 gl ){
-
gl.glClearColor(_red, _green, _blue, 1.0f); -->用定义的rgb来设设置背景色
-
gl.glClear(GL10.GL_COLOR_BUFFER_BIT); -->清空buffer
-
}
-
public void setColor(float r, float g, float b) { -->自己写的一个方法,来改变rgb颜色
-
_red = r; -->这样在onDrawFreme调用后就会在屏幕上显示出来
-
_green = g;
-
_blue = b;
-
}
-
- }
onSurfaceCreated() --> 在surface创建后调用
onSurfaceChanged() --> 在surface发生改变后调用,如从竖屏切换到横屏时
onDrawFrame() --> 当调用一个画图方法的时候调用
3. 运行代码后,在屏幕的不同位置点击,屏幕会显示不同的颜色
glDemo.rar(下载后不用改名)