OpenGL ES Tutorial for Android – Part I – Setting up the view
December 3rd, 2009 by Per-Erik Bergman — Android, Embedded
I'm going to write a couple of tutorials on using OpenGL ES on Android phones. The theory of OpenGL ES is the same on different devices so it should be quite easy to convert them to another platform.
我将写一些关于在Andoird 手机上使用OpenGL Es的教程。理论上OpenGL ES适用于不同的设备(平台),因此很容易被移植到其它平台。
I can't always remember where I found particular info so I might not always be able to give you the right reference. If you feel that I have borrowed stuff from you but have forgotten to add you as a reference, please e-mail me.
我常常忘了我所搜集的资料的来源与出处,所以(在某些资料方面)我可能不能给出正确的引用。如果您觉得我使用了您的资料而没有标明引用(位置),请发电子邮件给我。
In the code examples I will have two different links for each function. The actual function will be linked to the android documentation and after that I will also link the OpenGL documentations. Like this:
在示例代码中,我对每个函数将使用两种不同的链接。点击函数将链接到Android doc(Android doc太简单了,建议还是链接到OpenGL doc吧),在函数后面,我会添加一个到OpenGL docs的链接,如下:
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // OpenGL docs.
So, let's start.
好了,(言归正传)让我们这就开始OpenGL学习之旅吧。
In this tutorial I will show you how to set up your OpenGL ES view that’s always a good place to start.
在本教程中,我将(先)展示怎样来建立OpenGL ES界面,通常这是一个好的开始。
Setting up an OpenGL ES ViewSetting up a OpenGL view has never been hard and on Android it is still easy. There really are only two things you need to get started.
在Android中建立一个OpenGL视图非常简单,您需要做的只有两件事。
GLSurfaceViewGLSurfaceView is a API class in Android 1.5 that helps you write OpenGL ES applications.
GLSurfaceView是Android1.5中帮助您编写OpenGL ES应用程序的API类(,其具有以下功能)
· Providing the glue code to connect OpenGL ES to the View system.
· Providing the glue code to make OpenGL ES work with the Activity life-cycle.
· Making it easy to choose an appropriate frame buffer pixel format.
· Creating and managing a separate rendering thread to enable smooth animation.
· Providing easy-to-use debugging tools for tracing OpenGL ES API calls and checking for errors.
· 提供了OpenGL ES连接View系统的粘合代码。
· 提供了OpenGL ES与Activity生命周期协作的粘合代码。
· 易于选择合适的帧缓冲像素格式。
· 创建和管理独立的渲染线程来启用平滑动画(效果)
· 提供易于使用的调试工具来跟踪OpenGL ES API调用与检查错误。
If you want to get going fast with your OpenGL ES application this is where you should start.
The only function you need to call on is:
如果您想快速着手OpenGL ES应用程序,请从这里开始
您需要调用的唯一函数是:
public void setRenderer(GLSurfaceView.Renderer renderer)
Read more at: GLSurfaceView
GLSurfaceView.RendererGLSurfaceView.Renderer is a generic render interface. In your implementation of this renderer you should put all your calls to render a frame.
GLSurfaceView.Renderer是一个通用的渲染接口,您必须实现此类的抽象方法来画(动画中的)帧
There are three functions to implement:
您需要实现的三个方法如下:
// Called when the surface is created or recreated.
// 当平面创建或或重新创建的时候调用
public void onSurfaceCreated(GL10 gl, EGLConfig config)
// Called to draw the current frame.
// 画当前帧
public void onDrawFrame(GL10 gl)
// Called when the surface changed size.
// 当视图大小变更的时候调用,如屏幕横纵切换
public void onSurfaceChanged(GL10 gl, int width, int height)
onSurfaceCreatedHere it's a good thing to setup things that you don't change so often in the rendering cycle. Stuff like what color to clear the screen with, enabling z-buffer and so on.
推荐将一些在渲染周期中不会变更的代码放到此处,如设置屏幕初始颜色,开始Z轴缓冲等。
onDrawFrameHere is where the actual drawing take place.
在此函数中进行绘画(帧)
onSurfaceChangedIf your device supports flipping between landscape and portrait you will get a call to this function when it happens. What you do here is setting upp the new ratio.
Read more at: GLSurfaceView.Renderer
如果您的设备支持横竖屏切换,那么在切换发生时,您就需要在此方法中重新设置新的横纵比例了。
Putting it togetherFirst we create our activity, we keep it clean and simple.
首先,创建一个尽可能的简洁 的Activity。
package se.jayway.opengl.tutorial;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
public class TutorialPartI extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView view = new GLSurfaceView(this);
view.setRenderer(new OpenGLRenderer());
setContentView(view);
}
}
Our renderer takes little bit more work to setup, look at it and I will explain the code a bit more.
更多的render设置,请见我扩展的renderer类
package se.jayway.opengl.tutorial;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
public class OpenGLRenderer implements Renderer {
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.
* microedition.khronos.opengles.GL10, javax.microedition.khronos.
* egl.EGLConfig)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background color to black ( rgba ).
// 设置背景颜色为黑色 ( rgba ).
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // OpenGL docs.
// Enable Smooth Shading, default not really needed.
// 开启平滑阴影,实际上不需要(默认的shadeModel就是GL_SMOOTH)
gl.glShadeModel(GL10.GL_SMOOTH);// OpenGL docs.
// Depth buffer setup.
// 设置深度缓冲
gl.glClearDepthf(1.0f);// OpenGL docs.
// Enables depth testing.
// 启用深度测试
gl.glEnable(GL10.GL_DEPTH_TEST);// OpenGL docs.
// The type of depth testing to do.
// 设置深度测试类型
gl.glDepthFunc(GL10.GL_LEQUAL);// OpenGL docs.
// Really nice perspective calculations.
// 真实透视计算
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, // OpenGL docs.
GL10.GL_NICEST);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.
* microedition.khronos.opengles.GL10)
*/
public void onDrawFrame(GL10 gl) {
// Clears the screen and depth buffer.
// 清除屏幕和深度(Z轴)缓冲
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | // OpenGL docs.
GL10.GL_DEPTH_BUFFER_BIT);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.
* microedition.khronos.opengles.GL10, int, int)
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
// Sets the current view port to the new size.
//设置当前视窗新大小
gl.glViewport(0, 0, width, height);// OpenGL docs.
// Select the projection matrix
// 选择投影方式为透视投影
gl.glMatrixMode(GL10.GL_PROJECTION);// OpenGL docs.
// Reset the projection matrix
// 重置投影矩阵
gl.glLoadIdentity();// OpenGL docs.
// Calculate the aspect ratio of the window
// 计算窗口视角比例
GLU.gluPerspective(gl, 45.0f,
(float) width / (float) height,
0.1f, 100.0f);
// Select the modelview matrix
// 选择变换方式为modelview
gl.glMatrixMode(GL10.GL_MODELVIEW);// OpenGL docs.
// Reset the modelview matrix
// 重置变换矩阵
gl.glLoadIdentity();// OpenGL docs.
}
}
FullscreenJust add this lines in the OpenGLDemo class and you will get fullscreen.
只需要在OpenGLDemo类中添加如下代码,就可以让Activity全屏。建议还是在Manifest.xml中配置全屏
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // (NEW)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // (NEW)
... // Previous code.
}
This is pretty much all you need to get your view up and running. If you compile and run it you will see a nice black screen.
如果想要运行创建的OpenGL视图,以上就已经足够了,编译运行此应用,你可以看到一个纯黑色的屏幕。不过GLSurfaceView运行于独立的线程,所以需要将此线程同步到Android主线程中,做法是在Activity pause时,GLSurfaceView也pause;Activity resume时,GLSurfaceView线程也resume
ReferencesThe info used in this tutorial is collected from:
Android Developers
OpenGL ES 1.1 Reference Pages
You can download the source for this tutorial here: Tutorial_Part_I.zip
You can also checkout the code from: code.google.com
Next tutorial: OpenGL ES Tutorial for Android – Part II – Building a polygon
Per-Erik Bergman
Consultant at Jayway
OpenGL ES Tutorial for Android – Part IV – Adding colors
January 14th, 2010 by Per-Erik Bergman — Android, Embedded
Last tutorial was about transformations. This tutorial will be a short one. I'm going to talk about adding color to your mesh. I will continue with the source code from tutorial II.
本教程讲述的是着色
Adding color
3D models with no colors are pretty boring so let's add some color to it. In general colors need no explanation. OpenGL ES uses a color model called RGBA ( Red, Green, Blue and Alpha ). The first three are self explained. The fourth is transparency, how solid the color should be. If you like to read more about colors go to: RGB color model - Wikipedia, the free encyclopedia
3D模型如果没着色的话,那么看上去一点意思也没有。所以,我们给它们添加颜色。一般来说不需要对颜色展开解释。OpenGL ES使用的颜色模型为RGBA(红,绿,蓝,透明度)。前面三个就不需要解释了,第4个Alpha指的是透明度。(0,完全透明,1,完全不透明)
You might be familiar with defining colors with hex (#FF00FF) or with decimals (255, 0, 255) we will use 0..1 where 0 map to 0 (#00) and 1 map against 255 (#FF).
可能你对16进制或10进制的颜色表示法很熟悉。但在OpenGL中,使用的是0…1来表示,0映射为#00,1映射为#FF(255)
The easiest way of coloring meshes is called vertex coloring and I am going to show you two different ways of doing that. Flat coloring that gives one solid color and smooth coloring that will blend colors specified for each vertex. Texturing is also a way of giving your mesh colors but it is not vertex coloring so I will show you how to do that in a later tutorial.
老方式,从易而难,最简单的是对顶点着色,下面我将介绍两种方式。填充方式给每个顶点设置一个相同的颜色;平滑渐变方式为每个顶点设置一个渐变色。纹理映射也是一种着色方式,但不属于顶点着色范围。有关纹理映射,请见后续教程。
Flat coloring
Flat coloring is really easy just tell OpenGL ES what color to use when it is going to render. One thing to remember is that when you set the color OpenGL ES uses this color until you change the color. This means that if you have two different squares and you tell OpenGL ES to change the color right before the second square the first frame the two squares will have different color but the next rendered frame both squares will have the same color.
填充着色实在是太简单了,只需要告诉OpenGL ES渲染要使用的颜色就可以了。但要记住的是,设置的颜色一直生效,直到你更改了颜色。如,你有两个方块,你在画第二个方块之前更改了颜色,那么第一帧,两个方块颜色不一样,但是后面的帧,颜色就一样了。
To tell OpenGL ES what color to work with you use this command:
使用如下函数设置颜色
public abstract void glColor4f(float red, float green, float blue, float alpha)
The default values are: red = 1, green = 1, blue = 1 and alpha = 1. Those values are white, and that's why all the squares we previous made has a white color.
函数参数的默认值都为1,这也是为什么前面看到的方块都是白色的缘故。
Create a new class called FlatColoredSquare it should be identical to the Square class. Then in the FlatColoredSquare function draw, add this line:
创建一新新类名为FlatColoredSquare以区别于Square类。在绘画函数中添加下面这行
gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); // 0x8080FFFF
I usually add a comment like the one above ( // 0x8080FFFF ) because I am used to read that. It makes it easier for me when reviewing the code.
个人建议在注释中写上十六进制的颜色值,不仅易于读,而且在代码评审中也更加直观
It should now look like this:
public void draw(GL10 gl) {
gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);
...
Then change in the renderer so it uses the FlatColoredSquare instead of the Square.
public class OpenGLRenderer implements Renderer {
private FlatColoredSquare flatSquare; // CHANGED
public OpenGLRenderer() {
// Initialize our square.
flatSquare = new FlatColoredSquare(); // CHANGED
}
public void onDrawFrame(GL10 gl) {
...
flatSquare.draw(gl); // Don't forget to change this one.
...
}
Remember that anything rendered after you set a color uses the same color and that this spans over frames and will not be reset in-between.
注:在设置颜色之后,不需要再次设置颜色,即便是以后的各帧。
If you compile and run the application you will see one big flat colored blue square.
Just to give place to the smooth colored square coming up we move the flat square up.
public void onDrawFrame(GL10 gl) {
gl.glLoadIdentity();
// Translates 7 units into the screen and 1.5 units up.
gl.glTranslatef(0, 1.5f, -7);
// Draw our flat square.
flatSquare.draw(gl);
}
Notice that with flat coloring you don't need to tell OpenGL ES to turn it on or off. OpenGL ES uses flat coloring as a default way of coloring the meshes.
注:填充着色不需要告诉OpenGL ES开启或关闭此功能,OpenGL ES默认的就是填充方式
Smooth coloring
Smooth coloring is gained when you give each vertex its own color. OpenGL ES will interpolate the colors between the vertices and you will gain a smooth coloring effect. Just as with the flat coloring you tell OpenGL ES what to work with and it will be used as long as you don't say anything else.
平滑渐变着色对每个顶点都使用自己的颜色。OpenGL ES会在顶点之间插入颜色以得到平滑(渐变)颜色效果。与填充着色一样,设置的颜色可以被长期使用。
Create a new class called SmoothColoredSquare it should be identical to the Square class just as you did with the FlatColoredSquare. Modify the new class with this:
创建一个名为SmoothColoredSquare的新类
Define the colors you like your vertices to have.
定义顶点颜色
public class SmoothColoredSquare {
...
// The colors mapped to the vertices.
float[] colors = {
1f, 0f, 0f, 1f, // vertex 0 red
0f, 1f, 0f, 1f, // vertex 1 green
0f, 0f, 1f, 1f, // vertex 2 blue
1f, 0f, 1f, 1f, // vertex 3 magenta
};
...
The order of defining the colors are important since they map against the vertices so in this example above the first color (1f, 0f, 0f, 1f ) map against the top left vertex ( -1.0f, 1.0f, 0.0f ) the green against the bottom left vertex and the rest you can figure out. Hint: Look at the image above.
颜色的定义顺序很重要,它是和顶点一一对应的。如例中,红色(1f, 0f, 0f, 1f )对应于顶点0( -1.0f, 1.0f, 0.0f )。
And put them in a buffer just as we did with the vertices and indices.
如同顶点及顶点顺序数组一样,将它们放入字节缓冲中。
public SmoothColoredSquare() {
...
// float has 4 bytes, colors (RGBA) * 4 bytes
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
cbb.order(ByteOrder.nativeOrder());
colorBuffer = cbb.asFloatBuffer();
colorBuffer.put(colors);
colorBuffer.position(0);
}
Don't forget to add colorBuffer as a variable to the class as well.
别忘了添加colorBuffer类变量
// Our color buffer.
private FloatBuffer colorBuffer;
We also need to enable the color buffer and tell openGL where it is.
我们需要告诉OpenGL开启颜色字节缓冲
public void draw(GL10 gl) {
...
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
// Enable the color array buffer to be used during rendering.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // NEW LINE ADDED.
// Point out the where the color buffer is.
gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer); // NEW LINE ADDED.
gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
GL10.GL_UNSIGNED_SHORT, indexBuffer);
...
// Disable the color buffer.
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
...
}
Don't forget to disable the use of the color array. If you don't disable the color array both squares will be smooth colored. Try it.
注:别忘了最后禁止颜色缓冲,如果你忘了的话,前面的填充着色方块也会变成渐变着色的。
Let's use this new smooth square as well. Start by adding it to your renderer.
public class OpenGLRenderer implements Renderer {
private FlatColoredSquare flatSquare;
private SmoothColoredSquare smoothSquare; // NEW LINE ADDED.
public OpenGLRenderer() {
// Initialize our squares.
flatSquare = new FlatColoredSquare();
smoothSquare = new SmoothColoredSquare(); // NEW LINE ADDED.
}
We need to move the square down a bit so they don't collide.
public void onDrawFrame(GL10 gl) {
...
// Translate to end up under the flat square.
gl.glTranslatef(0, -3f, 0);
// Draw our smooth square.
smoothSquare.draw(gl);
}
Now if you compile and run the application you will see two squares, one solid blue and one smooth with different colors.
References
The info used in this tutorial is collected from:
Android Developers
OpenGL ES 1.1 Reference Pages
You can download the source for this tutorial here: Tutorial_Part_IV
You can also checkout the code from: code.google.com
Previous tutorial: OpenGL ES Tutorial for Android – Part III – Transformations
Next tutorial: OpenGL ES Tutorial for Android – Part V – More on Meshes
Per-Erik Bergman
Consultant at Jayway
拨打电话有两个关键的方面:
1. 在AndroidManifest.xml中添加uses-permission,<uses-permission android:name="android.permission.CALL_PHONE"/>
2. 通过自定义的Intent对象,带入"ACTION_CALL"这个ACTION,还要通过Uri.parse()的方法将用户输入的电话号码(Data)带入,最后调用startActivity方法。
package com.kevin.phone; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.R.bool; import android.app.Activity; import android.content.Intent; import android.graphics.Canvas.EdgeType; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Main extends Activity { private Button btn_call; private EditText number; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); number = (EditText) findViewById(R.id.editText1); btn_call = (Button) findViewById(R.id.button1); btn_call.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { String phone = number.getText().toString(); if(isValid(phone)){ // 构建Intent对象 Intent callIntent = new Intent( "android.intent.action.DIAL", Uri.parse("tel:" + phone)); startActivity(callIntent); number.setText(""); }else{ number.setText(""); Toast.makeText(Main.this, "非法电话号码", Toast.LENGTH_SHORT).show(); } } }); } // 检测电话号码输入是否合法 private boolean isValid(String input){ boolean flag = true; String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$"; String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$"; // 创建Pattern Pattern pattern = Pattern.compile(expression); // 将Pattern以参数传入Matcher作Regular expression Matcher matcher = pattern.matcher(input); Pattern pattern2 = Pattern.compile(expression2); Matcher matcher2 = pattern2.matcher(input); if(matcher.matches() || matcher2.matches()){ flag = true; }else{ flag = false; } return flag; } }