[android] 3D 공간위에 반투명인 2D 화면 출력하기 :: OPEN GL ES[SSISO Community]
 
SSISO 카페 SSISO Source SSISO 구직 SSISO 쇼핑몰 SSISO 맛집
추천검색어 : JUnit   Log4j   ajax   spring   struts   struts-config.xml   Synchronized   책정보   Ajax 마스터하기   우측부분

OPEN GL ES
[1]
등록일:2018-09-22 16:27:05 (0%)
작성자:
제목:[android] 3D 공간위에 반투명인 2D 화면 출력하기
이 샘플소스는 안드로이드 설치폴더에 android-sdk-windows/samples/android-8/ApiDemos 위치에 원본소스가 있습니다.

액티비티 화면을 3D 공간으로 구성하고, 그 위에 반투명 속성의 2D 화면을 출력하고 있습니다.

레이아웃은 xml 파일을 읽어들여 레이아웃을 배치하고 있습니다.

먼저 원하시는 패키지 경로에 SurfaceViewOverlay.java 액티비티 클래스 파일을 추가합니다.

/*
 * Copyright (C) 2007 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
 *
 *
 * 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.
 */

package net.korsoft.Test005;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

//Need the following import to get access to the app resources, since this
//class is in a sub-package.
import net.korsoft.Test005.R;

/**
 * Demonstration of overlays placed on top of a SurfaceView.
 * 
 * 3D 공간 위에 2D 화면을 출력하고 있습니다.
 * 레이아웃xml 파일을 구성할때, 3D 공간 레이아웃을 먼저 배치하고,
 * 그 밑으로 2D 화면레이아웃을 배치하여, 반투명 속성을 주어 뒤의
 * 3D 화면이 비치도록 레이아웃을 구성합니다.
 * 레이아웃은 xml 파일을 읽어들여 레이아웃을 배치하고 있습니다.
 */
public class SurfaceViewOverlay extends Activity {
    View mVictimContainer;
    View mVictim1;
    View mVictim2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // /res/layout/surface_view_overlay.xml 파일을 읽어서
        // 레이아웃을 구성하고 있습니다.
        setContentView(R.layout.surface_view_overlay);

        /*
         * 3D 공간을 다루는 뷰객체를 xml 파일에서 가져입니다.
         */
        GLSurfaceView glSurfaceView =
            (GLSurfaceView) findViewById(R.id.glsurfaceview);
        // 큐브 렌더링(실시간 그리기) 객체를 3D 공간객체에 설정합니다.
        glSurfaceView.setRenderer(new CubeRenderer(false));

        // Find the views whose visibility will change
        // 두개의 숨기기 버튼을 가져와 클릭 이벤트 처리를 하고 있습니다.
        mVictimContainer = findViewById(R.id.hidecontainer);
        mVictim1 = findViewById(R.id.hideme1);
        mVictim1.setOnClickListener(new HideMeListener(mVictim1));
        mVictim2 = findViewById(R.id.hideme2);
        mVictim2.setOnClickListener(new HideMeListener(mVictim2));

        // Find our buttons
        // 하단의 세개의 버튼을 가져와 클릭이벤트 처리를 합니다.
        // vis / invis / gone 세개의 버튼에 대한 처리입니다.
        Button visibleButton = (Button) findViewById(R.id.vis);
        Button invisibleButton = (Button) findViewById(R.id.invis);
        Button goneButton = (Button) findViewById(R.id.gone);

        // Wire each button to a click listener
        visibleButton.setOnClickListener(mVisibleListener);
        invisibleButton.setOnClickListener(mInvisibleListener);
        goneButton.setOnClickListener(mGoneListener);
    }

    @Override
    protected void onResume() {
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onResume();
    }

    @Override
    protected void onPause() {
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onPause();
    }
    
    // 클릭 이벤트 핸들러 메소드 정의...
    class HideMeListener implements OnClickListener {
        final View mTarget;

        HideMeListener(View target) {
            mTarget = target;
        }

        public void onClick(View v) {
            mTarget.setVisibility(View.INVISIBLE);
        }

    }

    OnClickListener mVisibleListener = new OnClickListener() {
        public void onClick(View v) {
            mVictim1.setVisibility(View.VISIBLE);
            mVictim2.setVisibility(View.VISIBLE);
            mVictimContainer.setVisibility(View.VISIBLE);
        }
    };

    OnClickListener mInvisibleListener = new OnClickListener() {
        public void onClick(View v) {
            mVictim1.setVisibility(View.INVISIBLE);
            mVictim2.setVisibility(View.INVISIBLE);
            mVictimContainer.setVisibility(View.INVISIBLE);
        }
    };

    OnClickListener mGoneListener = new OnClickListener() {
        public void onClick(View v) {
            mVictim1.setVisibility(View.GONE);
            mVictim2.setVisibility(View.GONE);
            mVictimContainer.setVisibility(View.GONE);
        }
    };
}


3D 공간에 큐브를 출력하는 내용을 정의하는 CubeRenderer.java 파일을 추가합니다.

/*
 * Copyright (C) 2007 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
 *
 *
 * 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.
 */

package net.korsoft.Test005;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;

/**
 * Render a pair of tumbling cubes.
 */

class CubeRenderer implements GLSurfaceView.Renderer {
    public CubeRenderer(boolean useTranslucentBackground) {
        mTranslucentBackground = useTranslucentBackground;
        mCube = new Cube();
    }

    public void onDrawFrame(GL10 gl) {
        /*
         * Usually, the first thing one might want to do is to clear
         * the screen. The most efficient way of doing this is to use
         * glClear().
         */

        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        /*
         * Now we're ready to draw some 3D objects
         */

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        gl.glTranslatef(0, 0, -3.0f);
        gl.glRotatef(mAngle,        0, 1, 0);
        gl.glRotatef(mAngle*0.25f,  1, 0, 0);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

        mCube.draw(gl);

        gl.glRotatef(mAngle*2.0f, 0, 1, 1);
        gl.glTranslatef(0.5f, 0.5f, 0.5f);

        mCube.draw(gl);

        mAngle += 1.2f;
    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {
         gl.glViewport(0, 0, width, height);

         /*
          * Set our projection matrix. This doesn't have to be done
          * each time we draw, but usually a new projection needs to
          * be set when the viewport is resized.
          */

         float ratio = (float) width / height;
         gl.glMatrixMode(GL10.GL_PROJECTION);
         gl.glLoadIdentity();
         gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        gl.glDisable(GL10.GL_DITHER);

        /*
         * Some one-time OpenGL initialization can be made here
         * probably based on features of this particular context
         */
         gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
                 GL10.GL_FASTEST);

         if (mTranslucentBackground) {
             gl.glClearColor(0,0,0,0);
         } else {
             gl.glClearColor(1,1,1,1);
         }
         gl.glEnable(GL10.GL_CULL_FACE);
         gl.glShadeModel(GL10.GL_SMOOTH);
         gl.glEnable(GL10.GL_DEPTH_TEST);
    }
    private boolean mTranslucentBackground;
    private Cube mCube;
    private float mAngle;
}


큐브 물체의 좌표를 설정하고, 출력처리를 정의하는 Cube.java 파일을 추가합니다.

/*
 * Copyright (C) 2007 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
 *
 *
 * 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.
 */

package net.korsoft.Test005;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import javax.microedition.khronos.opengles.GL10;

/**
 * A vertex shaded cube.
 */
class Cube
{
    public Cube()
    {
        int one = 0x10000;
        int vertices[] = {
                -one, -one, -one,
                one, -one, -one,
                one,  one, -one,
                -one,  one, -one,
                -one, -one,  one,
                one, -one,  one,
                one,  one,  one,
                -one,  one,  one,
        };

        int colors[] = {
                0,    0,    0,  one,
                one,    0,    0,  one,
                one,  one,    0,  one,
                0,  one,    0,  one,
                0,    0,  one,  one,
                one,    0,  one,  one,
                one,  one,  one,  one,
                0,  one,  one,  one,
        };

        byte indices[] = {
                0, 4, 5,    0, 5, 1,
                1, 5, 6,    1, 6, 2,
                2, 6, 7,    2, 7, 3,
                3, 7, 4,    3, 4, 0,
                4, 7, 6,    4, 6, 5,
                3, 0, 1,    3, 1, 2
        };

        // Buffers to be passed to gl*Pointer() functions
        // must be direct, i.e., they must be placed on the
        // native heap where the garbage collector cannot
        // move them.
        //
        // Buffers with multi-byte datatypes (e.g., short, int, float)
        // must have their byte order set to native order

        ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asIntBuffer();
        mVertexBuffer.put(vertices);
        mVertexBuffer.position(0);

        ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
        cbb.order(ByteOrder.nativeOrder());
        mColorBuffer = cbb.asIntBuffer();
        mColorBuffer.put(colors);
        mColorBuffer.position(0);

        mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
        mIndexBuffer.put(indices);
        mIndexBuffer.position(0);
    }

    public void draw(GL10 gl)
    {
        gl.glFrontFace(gl.GL_CW);
        gl.glVertexPointer(3, gl.GL_FIXED, 0, mVertexBuffer);
        gl.glColorPointer(4, gl.GL_FIXED, 0, mColorBuffer);
        gl.glDrawElements(gl.GL_TRIANGLES, 36, gl.GL_UNSIGNED_BYTE, mIndexBuffer);
    }

    private IntBuffer   mVertexBuffer;
    private IntBuffer   mColorBuffer;
    private ByteBuffer  mIndexBuffer;
}


액티비티의 레이아웃을 정의하는 /res/layout/surface_view_overlay.xml 파일을 추가해줍니다.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 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
  
  
     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.
-->

<!-- Demonstrates changing view visibility. See corresponding Java code. -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <!-- Here is where we put the SurfaceView, in a frame so that we can
         stack other views on top of it. -->
    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1">

        <!-- 3D 공간입니다. 이 공간에서 큐브물체가 계속 돌아가게 됩니다. -->
        <android.opengl.GLSurfaceView android:id="@+id/glsurfaceview"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

  <!-- 
   위의 3D 공간 위에 표시될 2D 레이아웃입니다. 중앙에 버튼 두개를 배치하고 있습니다.
   뒤에 3D 화면에서 큐브가 돌아가는 영상이 반투명하게 비추게 됩니다.
   android:visibility="gone" 속성을 주어 처음에 보이지 앖게 했다가,
   버튼을 눌렀을때 3D 화면 위에 보이도록 배치하게 됩니다.
   android:background="@drawable/translucent_background" 속성으로
   뒤의 3D 화면이 비치도록 반투명 옵션을 줍니다. 
  -->
        <LinearLayout android:id="@+id/hidecontainer"
                android:orientation="vertical"
                android:visibility="gone"
                android:background="@drawable/translucent_background"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            <Button android:id="@+id/hideme1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:visibility="gone"
                    android:text="@string/hide_me"/>
            
            <Button android:id="@+id/hideme2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:visibility="gone"
                    android:text="@string/hide_me"/>
                    
        </LinearLayout>
        
    </FrameLayout>
    
    <!-- 하단에 배치되는 버튼 세개, hide / invis / gone 버튼 세개의 레이아웃 배치입니다. -->
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center">

        <Button android:id="@+id/vis"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/visibility_1_vis"/>

        <Button android:id="@+id/invis"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/visibility_1_invis"/>

        <Button android:id="@+id/gone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/visibility_1_gone"/>

    </LinearLayout>

</LinearLayout>


액티비티의 배경을 투명하게 하기위한 설정을 하는 /res/values/styles.xml 파일을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 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
  
  
     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.
-->

<resources>
    <!-- Base application theme is the default theme. -->
    <style name="Theme" parent="android:Theme">
    </style>
    
    <!-- A theme that has a translucent background.  Here we explicitly specify
         that this theme is to inherit from the system's translucent theme,
         which sets up various attributes correctly. -->
    <style name="Theme.Translucent" parent="android:style/Theme.Translucent">
        <item name="android:windowBackground">@drawable/translucent_background</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:colorForeground">#fff</item>
    </style>

</resources>


액티비티의 배경을 투명하게 하기위한 반투명색을 정의하는 /res/values/colors.xml 파일을 추가해줍니다.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 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
  
  
     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.
-->

<resources>
<drawable name="screen_background_black">#ff000000</drawable>
    <drawable name="translucent_background">#e0000000</drawable>
    <drawable name="transparent_background">#00000000</drawable>

</resources>


문자열 리소스를 설정하는 /res/values/strings.xml 파일을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Test005Activity!</string>
    <string name="app_name">Test005</string>
    <string name="visibility_1_vis">Vis</string>
    <string name="visibility_1_invis">Invis</string>
    <string name="visibility_1_gone">Gone</string>
    <string name="hide_me">Hide Me!</string>
</resources>


마지막으로 AndroidManifest.xml 파일을 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
      package="net.korsoft.Test005"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <activity android:name=".SurfaceViewOverlay"
                android:label="Graphics/SurfaceView Overlay">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
[본문링크] [android] 3D 공간위에 반투명인 2D 화면 출력하기
[1]
코멘트(이글의 트랙백 주소:/cafe/tb_receive.php?no=34847
작성자
비밀번호

 

SSISOCommunity

[이전]

Copyright byCopyright ⓒ2005, SSISO Community All Rights Reserved.