(三)繪制形狀(Drawing Shapes)

原文:https://developer.android.com/training/graphics/opengl/draw.html

After you define shapes to be drawn with OpenGL, you probably want to draw them. Drawing shapes with the OpenGL ES 2.0 takes a bit more code than you might imagine, because the API provides a great deal of control over the graphics rendering pipeline.
定義了形狀之后,接下來就是繪制形狀博个。繪制這些形狀需要的代碼比你想象的要多一些祸泪,因?yàn)橛写罅靠刂评L圖管道控制的API簇秒。

This lesson explains how to draw the shapes you defined in the previous lesson using the OpenGL ES 2.0 API.
這里學(xué)習(xí)如何用OpenGL ES 2.0 API 繪制上一課節(jié)定義的圖形。

Initialize Shapes

初始化形狀

Before you do any drawing, you must initialize and load the shapes you plan to draw. Unless the structure (the original coordinates) of the shapes you use in your program change during the course of execution, you should initialize them in the onSurfaceCreated() method of your renderer for memory and processing efficiency.
在繪制之前墓造,必須初始化和加載那些要畫的形狀媒区。為了提高內(nèi)存和處理效率靡砌,應(yīng)該在renderer 的方法onSurfaceCreated() 里面對(duì)形狀進(jìn)行初始化已脓,除非形狀的初始坐標(biāo)在執(zhí)行過程中會(huì)改變。

public class MyGLRenderer implements GLSurfaceView.Renderer {

    ...
    private Triangle mTriangle;
    private Square   mSquare;

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        ...

        // initialize a triangle
        mTriangle = new Triangle();
        // initialize a square
        mSquare = new Square();
    }
    ...
}

Draw a Shape

繪制形狀

Drawing a defined shape using OpenGL ES 2.0 requires a significant amount of code, because you must provide a lot of details to the graphics rendering pipeline. Specifically, you must define the following:
使用OpenGL ES 2.0繪制形狀需要大量的代碼通殃,因?yàn)槟阈枰獮槔L制管道提供大量的信息度液。尤其需要提供以下的信息:

  • Vertex Shader - OpenGL ES graphics code for rendering the vertices of a shape.
    頂點(diǎn)Shader-OpenGL 用來繪制形狀的頂點(diǎn)

  • Fragment Shader - OpenGL ES code for rendering the face of a shape with colors or textures.
    碎片shader-OpenGL ES用來繪形狀面的顏色和texture(亂猜的厕宗,專業(yè)術(shù)語暫時(shí)跳過??)

  • Program - An OpenGL ES object that contains the shaders you want to use for drawing one or more shapes.
    Program- 一個(gè)OpenGL ES對(duì)象,包含了你需要用來繪制形狀的shaders.

You need at least one vertex shader to draw a shape and one fragment shader to color that shape. These shaders must be complied and then added to an OpenGL ES program, which is then used to draw the shape. Here is an example of how to define basic shaders you can use to draw a shape in the Triangle class:
你至少需要一個(gè)頂點(diǎn)shader來繪制形狀堕担,一個(gè)碎片shader來給這個(gè)形狀著色已慢。這些shaders必須先編譯,然后添加到一個(gè)OpenGL ES program霹购,然后用這個(gè)program來繪制形狀佑惠。下面這個(gè)例子描述了怎么定義一些基本的shaders來繪制三角形。

public class Triangle {

    private final String vertexShaderCode =
        "attribute vec4 vPosition;" +
        "void main() {" +
        "  gl_Position = vPosition;" +
        "}";

    private final String fragmentShaderCode =
        "precision mediump float;" +
        "uniform vec4 vColor;" +
        "void main() {" +
        "  gl_FragColor = vColor;" +
        "}";

    ...
}

Shaders contain OpenGL Shading Language (GLSL) code that must be compiled prior to using it in the OpenGL ES environment. To compile this code, create a utility method in your renderer class:
Shaders包含OpenGL Shading語言代碼齐疙,在OpenGL ES環(huán)境中使用這些代碼之前必須先編譯膜楷。在render類里建立一個(gè)utility方法來編譯這些代碼。

public static int loadShader(int type, String shaderCode){

    // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
    int shader = GLES20.glCreateShader(type);

    // add the source code to the shader and compile it
    GLES20.glShaderSource(shader, shaderCode);
    GLES20.glCompileShader(shader);

    return shader;
}

In order to draw your shape, you must compile the shader code, add them to a OpenGL ES program object and then link the program. Do this in your drawn object’s constructor, so it is only done once.
繪制形狀時(shí)贞奋,你必須先編譯shader代碼赌厅,然后把編譯好的shader加到OpenGL ES program對(duì)象里,再連接program. 這些操作只需要做一次轿塔,所以放在形狀對(duì)象的構(gòu)造器中特愿。

  • Note: Compiling OpenGL ES shaders and linking programs is expensive in terms of CPU cycles and processing time, so you should avoid doing this more than once. If you do not know the content of your shaders at runtime, you should build your code such that they only get created once and then cached for later use.
    編譯OpenGL ES shaders和連接program很耗CPU資源,所以避免重復(fù)操作勾缭。如果在runtime時(shí)不知道shaders的內(nèi)容揍障,你應(yīng)該確保這些shaders只創(chuàng)建一次,并且緩存以便后續(xù)使用(??你妹漫拭,連個(gè)粟子都不舉)
public class Triangle() {
    ...

    private final int mProgram;

    public Triangle() {
        ...

        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
                                        vertexShaderCode);
        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
                                        fragmentShaderCode);

        // create empty OpenGL ES Program
        mProgram = GLES20.glCreateProgram();

        // add the vertex shader to program
        GLES20.glAttachShader(mProgram, vertexShader);

        // add the fragment shader to program
        GLES20.glAttachShader(mProgram, fragmentShader);

        // creates OpenGL ES program executables
        GLES20.glLinkProgram(mProgram);
    }
}

At this point, you are ready to add the actual calls that draw your shape. Drawing shapes with OpenGL ES requires that you specify several parameters to tell the rendering pipeline what you want to draw and how to draw it. Since drawing options can vary by shape, it's a good idea to have your shape classes contain their own drawing logic.
現(xiàn)在你可以真正地開始畫圖了亚兄。用OpenGL ES繪圖時(shí),需要你明確一些參數(shù)采驻,告訴繪圖管道你想要畫什么审胚,怎么畫。因?yàn)椴煌膱D形需要的參數(shù)不一樣礼旅,所以把繪圖相關(guān)的邏輯讓在不同的形狀類里面比較方便膳叨。

Create a draw() method for drawing the shape. This code sets the position and color values to the shape’s vertex shader and fragment shader, and then executes the drawing function.
創(chuàng)建一個(gè)draw()方法用來繪圖。在里面設(shè)定頂點(diǎn)shader的位置值和碎片shader的顏色值痘系。然后調(diào)用這個(gè)方法菲嘴。

private int mPositionHandle;
private int mColorHandle;

private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex

public void draw() {
    // Add program to OpenGL ES environment
    GLES20.glUseProgram(mProgram);

    // get handle to vertex shader's vPosition member
    mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

    // Enable a handle to the triangle vertices
    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Prepare the triangle coordinate data
    GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                                 GLES20.GL_FLOAT, false,
                                 vertexStride, vertexBuffer);

    // get handle to fragment shader's vColor member
    mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

    // Set color for drawing the triangle
    GLES20.glUniform4fv(mColorHandle, 1, color, 0);

    // Draw the triangle
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);

    // Disable vertex array
    GLES20.glDisableVertexAttribArray(mPositionHandle);
}

Once you have all this code in place, drawing this object just requires a call to the draw() method from within your renderer’s onDrawFrame() method:
一旦你寫好了這些代碼,在render的onDrawFrame()方法中調(diào)用就好了汰翠。

public void onDrawFrame(GL10 unused) {
    ...

    mTriangle.draw();
}

When you run the application, it should look something like this:
當(dāng)你運(yùn)行這個(gè)應(yīng)用龄坪,看起來是這樣子的。


Figure 1. Triangle drawn without a projection or camera view.

There are a few problems with this code example. First of all, it is not going to impress your friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen orientation of the device. The reason the shape is skewed is due to the fact that the object’s vertices have not been corrected for the proportions of the screen area where the GLSurfaceView is displayed. You can fix that problem using a projection and camera view in the next lesson.
這個(gè)例子還有一些問題复唤。首先健田,很low; 然后三角形有點(diǎn)變形,當(dāng)屏幕旋轉(zhuǎn)后佛纫,形狀也會(huì)變化妓局。之所以會(huì)變形是因?yàn)樽芊牛陲@示GLSurfaceView的屏幕上,三角形的頂點(diǎn)沒有設(shè)置正確好爬。在下節(jié)課中局雄,你可以用投影和相機(jī)視角來解決這個(gè)問題。??

Lastly, the triangle is stationary, which is a bit boring. In the Adding Motion lesson, you make this shape rotate and make more interesting use of the OpenGL ES graphics pipeline.
最后存炮,三角形是固定的炬搭,沒意思。在附加的運(yùn)動(dòng)課程中穆桂,你可以讓三角形旋轉(zhuǎn)尚蝌,利用OpenGL ES繪圖管道做一些更有意思的事情。下一課

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末充尉,一起剝皮案震驚了整個(gè)濱河市飘言,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌驼侠,老刑警劉巖姿鸿,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異倒源,居然都是意外死亡苛预,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門笋熬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來热某,“玉大人,你說我怎么就攤上這事胳螟∥舨觯” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵糖耸,是天一觀的道長(zhǎng)秘遏。 經(jīng)常有香客問我,道長(zhǎng)嘉竟,這世上最難降的妖魔是什么邦危? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮舍扰,結(jié)果婚禮上倦蚪,老公的妹妹穿的比我還像新娘。我一直安慰自己边苹,他們只是感情好陵且,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著勾给,像睡著了一般滩报。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上播急,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天脓钾,我揣著相機(jī)與錄音,去河邊找鬼桩警。 笑死可训,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的捶枢。 我是一名探鬼主播握截,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼烂叔!你這毒婦竟也來了谨胞?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤蒜鸡,失蹤者是張志新(化名)和其女友劉穎胯努,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體逢防,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叶沛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了忘朝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片灰署。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖局嘁,靈堂內(nèi)的尸體忽然破棺而出溉箕,到底是詐尸還是另有隱情,我是刑警寧澤悦昵,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布约巷,位于F島的核電站,受9級(jí)特大地震影響旱捧,放射性物質(zhì)發(fā)生泄漏独郎。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一枚赡、第九天 我趴在偏房一處隱蔽的房頂上張望氓癌。 院中可真熱鬧,春花似錦贫橙、人聲如沸贪婉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)疲迂。三九已至才顿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間尤蒿,已是汗流浹背郑气。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留腰池,地道東北人尾组。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像示弓,于是被迫代替她去往敵國(guó)和親讳侨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容