You are on page 1of 12

6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.

(https://androidcoffee.com)

Tutorialhowtodraw3DphotocubeinAndroidStudio1.4
Learnfromthistutorialhowtodraw3DcubewithOpenGL,rotateit,putsiximages,oneoneachsideofitandplayasoundonclickinAndroidStudioversion1.4.
CreateNewProjectwithApplicationname:PhotoCubeMinimumSDK:API9Android2.3(Gingerbread).
Add6picturesfromcomputer,inprojectfolderres>drawable:pic1.jpg,pic2.jpg,pic3.jpg,pic4.jpg,pic5.jpg,pic6.jpg.
CreateNewJavaClassMyGLActivityandcompletethecode.

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 1/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4

importandroid.app.Activity;
importandroid.opengl.GLSurfaceView;
importandroid.os.Bundle;

publicclassMyGLActivityextendsActivity{

privateGLSurfaceViewglView;//useGLSurfaceView

//Callbackwhentheactivityisstarted,toinitializetheview
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
glView=newGLSurfaceView(this);//AllocateaGLSurfaceView
glView.setRenderer(newMyGLRenderer(this));//Useacustomrenderer
this.setContentView(glView);//ThisactivitysetstoGLSurfaceView
}

//Callbackwhentheactivityisgoingintothebackground
@Override
protectedvoidonPause(){
super.onPause();
glView.onPause();
}

//CallbackafteronPause()
@Override
protectedvoidonResume(){
super.onResume();
glView.onResume();
}
}

CreateNewJavaClassMyGLRendererandcompletethecode.

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 2/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4

importjavax.microedition.khronos.egl.EGLConfig;
importjavax.microedition.khronos.opengles.GL10;
importandroid.content.Context;
importandroid.opengl.GLSurfaceView;
importandroid.opengl.GLU;

publicclassMyGLRendererimplementsGLSurfaceView.Renderer{
privatePhotoCubecube;//(NEW)
privatestaticfloatangleCube=0;//rotationalangleindegreeforcube
privatestaticfloatspeedCube=0.5f;//rotationalspeedforcube

//Constructor
publicMyGLRenderer(Contextcontext){

cube=newPhotoCube(context);//(NEW)
}

//Callbackwhenthesurfaceisfirstcreatedorrecreated.
@Override
publicvoidonSurfaceCreated(GL10gl,EGLConfigconfig){
gl.glClearColor(0.0f,0.0f,0.0f,1.0f);//Setcolor'sclearvaluetoblack
gl.glClearDepthf(1.0f);//Setdepth'sclearvaluetofarthest
gl.glEnable(GL10.GL_DEPTH_TEST);//Enablesdepthbufferforhiddensurfaceremoval
gl.glDepthFunc(GL10.GL_LEQUAL);//Thetypeofdepthtestingtodo
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_NICEST);//niceperspectiveview
gl.glShadeModel(GL10.GL_SMOOTH);//Enablesmoothshadingofcolor
gl.glDisable(GL10.GL_DITHER);//Disableditheringforbetterperformance

//SetupTexture,eachtimethesurfaceiscreated(NEW)
cube.loadTexture(gl);//Loadimagesintotextures(NEW)
gl.glEnable(GL10.GL_TEXTURE_2D);//Enabletexture(NEW)
}

//CallbackafteronSurfaceCreated()orwheneverthewindow'ssizechanges
@Override
publicvoidonSurfaceChanged(GL10gl,intwidth,intheight){
if(height==0)height=1;//Topreventdividebyzero
floataspect=(float)width/height;

//Settheviewport(displayarea)tocovertheentirewindow
gl.glViewport(0,0,width,height);

//Setupperspectiveprojection,withaspectratiomatchesviewport
gl.glMatrixMode(GL10.GL_PROJECTION);//Selectprojectionmatrix
gl.glLoadIdentity();//Resetprojectionmatrix
http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 3/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4
gl.glLoadIdentity();//Resetprojectionmatrix
//Useperspectiveprojection
GLU.gluPerspective(gl,45,aspect,0.1f,100.f);

gl.glMatrixMode(GL10.GL_MODELVIEW);//Selectmodelviewmatrix
gl.glLoadIdentity();//Reset

//YouOpenGL|ESdisplayresizingcodehere
//......
}

//Callbacktodrawthecurrentframe.
@Override
publicvoidonDrawFrame(GL10gl){

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

//RendertheCube
gl.glLoadIdentity();//Resetthemodelviewmatrix
gl.glTranslatef(0.0f,0.0f,6.0f);//Translateintothescreen
gl.glRotatef(angleCube,0.15f,1.0f,0.3f);//Rotate
cube.draw(gl);

//Updatetherotationalangleaftereachrefresh.
angleCube+=speedCube;
}
}

CreateNewJavaClassPhotoCubeandcompletethecode.

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 4/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4

importjava.nio.ByteBuffer;
importjava.nio.ByteOrder;
importjava.nio.FloatBuffer;
importjavax.microedition.khronos.opengles.GL10;
importandroid.content.Context;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.opengl.GLUtils;
/*
*Aphotocubewith6pictures(textures)onits6faces.
*/
publicclassPhotoCube{
privateFloatBuffervertexBuffer;//VertexBuffer

privateFloatBuffertexBuffer;//TextureCoordsBuffer

privateintnumFaces=6;
privateint[]imageFileIDs={//ImagefileIDs
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6
};
privateint[]textureIDs=newint[numFaces];
privateBitmap[]bitmap=newBitmap[numFaces];
privatefloatcubeHalfSize=1.2f;

//ConstructorSetupthevertexbuffer
publicPhotoCube(Contextcontext){
//Allocatevertexbuffer.Anfloathas4bytes
ByteBuffervbb=ByteBuffer.allocateDirect(12*4*numFaces);
vbb.order(ByteOrder.nativeOrder());
vertexBuffer=vbb.asFloatBuffer();

//Readimages.Findtheaspectratioandadjusttheverticesaccordingly.
for(intface=0;face<numFaces;face++){
bitmap[face]=BitmapFactory.decodeStream(
context.getResources().openRawResource(imageFileIDs[face]));
intimgWidth=bitmap[face].getWidth();
intimgHeight=bitmap[face].getHeight();
floatfaceWidth=2.0f;
floatfaceHeight=2.0f;
//Adjustforaspectratio
http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 5/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4
//Adjustforaspectratio
if(imgWidth>imgHeight){
faceHeight=faceHeight*imgHeight/imgWidth;
}else{
faceWidth=faceWidth*imgWidth/imgHeight;
}
floatfaceLeft=faceWidth/2;
floatfaceRight=faceLeft;
floatfaceTop=faceHeight/2;
floatfaceBottom=faceTop;

//Definetheverticesforthisface
float[]vertices={
faceLeft,faceBottom,0.0f,//0.leftbottomfront

faceRight,faceBottom,0.0f,//1.rightbottomfront
faceLeft,faceTop,0.0f,//2.lefttopfront
faceRight,faceTop,0.0f,//3.righttopfront
};
vertexBuffer.put(vertices);//Populate
}
vertexBuffer.position(0);//Rewind

//Allocatetexturebuffer.Anfloathas4bytes.Repeatfor6faces.
float[]texCoords={
0.0f,1.0f,//A.leftbottom
1.0f,1.0f,//B.rightbottom
0.0f,0.0f,//C.lefttop
1.0f,0.0f//D.righttop
};
ByteBuffertbb=ByteBuffer.allocateDirect(texCoords.length*4*numFaces);
tbb.order(ByteOrder.nativeOrder());
texBuffer=tbb.asFloatBuffer();
for(intface=0;face<numFaces;face++){
texBuffer.put(texCoords);
}
texBuffer.position(0);//Rewind
}

//Rendertheshape
publicvoiddraw(GL10gl){
gl.glFrontFace(GL10.GL_CCW);

gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3,GL10.GL_FLOAT,0,vertexBuffer);
http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 6/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4
gl.glVertexPointer(3,GL10.GL_FLOAT,0,vertexBuffer);
gl.glTexCoordPointer(2,GL10.GL_FLOAT,0,texBuffer);

//front
gl.glPushMatrix();
gl.glTranslatef(0f,0f,cubeHalfSize);
gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[0]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,0,4);
gl.glPopMatrix();

//left
gl.glPushMatrix();
gl.glRotatef(270.0f,0f,1f,0f);
gl.glTranslatef(0f,0f,cubeHalfSize);

gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[1]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,4,4);
gl.glPopMatrix();

//back
gl.glPushMatrix();
gl.glRotatef(180.0f,0f,1f,0f);
gl.glTranslatef(0f,0f,cubeHalfSize);
gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[2]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,8,4);
gl.glPopMatrix();

//right
gl.glPushMatrix();
gl.glRotatef(90.0f,0f,1f,0f);
gl.glTranslatef(0f,0f,cubeHalfSize);
gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[3]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,12,4);
gl.glPopMatrix();

//top
gl.glPushMatrix();
gl.glRotatef(270.0f,1f,0f,0f);
gl.glTranslatef(0f,0f,cubeHalfSize);
gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[4]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,16,4);
gl.glPopMatrix();

//bottom
gl.glPushMatrix();
gl.glRotatef(90.0f,1f,0f,0f);
http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 7/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4
gl.glRotatef(90.0f,1f,0f,0f);
gl.glTranslatef(0f,0f,cubeHalfSize);
gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[5]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP,20,4);
gl.glPopMatrix();

gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}

//Loadimagesinto6GLtextures
publicvoidloadTexture(GL10gl){
gl.glGenTextures(6,textureIDs,0);//GeneratetextureIDarrayfor6IDs

//GenerateOpenGLtextureimages
for(intface=0;face<numFaces;face++){
gl.glBindTexture(GL10.GL_TEXTURE_2D,textureIDs[face]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,GL10.GL_TEXTURE_MAG_FILTER,GL10.GL_LINEAR);
//BuildTexturefromloadedbitmapforthecurrentlybindtextureID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D,0,bitmap[face],0);
bitmap[face].recycle();
}
}
}

ModifycodeinAndroidManifest.xmlfile.

<application
android:allowBackup="true"

android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activityandroid:name="MyGLActivity">
<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</activity>
</application>

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 8/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4

RuntheappinEmulator.

Innextstepslearnhowtoaddsoundonclickandhowtostopsoundwhenexitapp.
Inresfolder,CreateNewDirectory:raw.
Addanmp3withnamesound.mp3infolderraw.
CompletecodeforplayasoundonclickinMyGLActivity.javafile:

privateMediaPlayermp;

InonCreateaddcode:

glView.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewv){
mp=MediaPlayer.create(MyGLActivity.this,R.raw.sound);
mp.start();
}
});

Addcodetostopsoundwhenexitapp.

mp.release();

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 9/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4

(http://androidcoffee.com/wpcontent/uploads/2015/11/photocube.jpg)

Runappandsee3Dcubethatrotatesandhasoneachsideofit,oneofthephotosyouveincludedintheprojectandonclickitheardthesoundalsoincludedinproject.

Watchthevideotutorialtodraw3DphotocubeinAndroidStudioversion1.4:

How to draw 3D photo cube in Android Studio 1.4

Downloadfreeappphotocube.apkfromhere(http://androidcoffee.com/wpcontent/uploads/projecs/photocube.apk)andinstallitonyourdevicetosee3Dcubewith6imagesoneachside,
rotatingandplayingasoundontouch.

Forfurtherquestionsleaveamessage.

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 10/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4

PreviousPost(https://androidcoffee.com/playvideo/) NextPost(https://androidcoffee.com/photocube3d/)

2Comments
YoucanfollowanyresponsestothisentrythroughtheRSS2.0(https://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/feed/)feed.

Mohammed(May28,2016)

Hello
Thanksforthetuto,itwasreallyhelpful.
Iwannaknowtoaddasoundforeachsideofthecube.
Cordially

Reply(https://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/?replytocom=89#respond)

SunilVishwakarma(December13,2016)

nicetutorailbutthepointishowtoknowwhichfaceistouched?

Reply(https://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/?replytocom=159#respond)

LeaveaReply
Youremailaddresswillnotbepublished.Requiredfieldsaremarked*

Yourcomment

Yourname

Youremailaddress

Yourwebsiteurl

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 11/12
6/16/2017 Tutorialhowtodraw3DphotocubeinAndroidStudio1.4
Yourwebsiteurl

BlueCaptchaImage Refresh

Captcha*

PostComment

AllaboutANDROID
Applications(https://androidcoffee.com/category/androidapplications/)(19)
Tutorials(https://androidcoffee.com/category/androidtutorials/)(35)

RecentPosts
TutorialHowtoPlayYouTubeVideousingYouTubePlayerFragmentwithYouTubeAndroidPlayerAPIinAndroidStudio2.1.2(https://androidcoffee.com/youtubeplayerfragment/)
TutorialHowtoPlayYouTubeVideousingYouTubeAndroidPlayerAPIinAndroidStudio(https://androidcoffee.com/tutorialplayyoutubevideo/)
FunnyToyoSurpriseYouTubeChannelPlaylistVideosforKidsAndroidapp(https://androidcoffee.com/funnytoyosurpriseyoutubechannelplaylistvideosforkidsandroidapp/)
TutorialHowtoPlayVideosPLAYLISTYouTubeusingYouTubeAndroidPlayerAPIinAndroidStudio(https://androidcoffee.com/tutorialplayvideosplaylistyoutube/)
TutorialhowtozoomphotoonImageViewinAndroidStudio1.5.1(https://androidcoffee.com/tutorialhowtozoomphotoonimageviewinandroidstudio151/)

Megusta Compartir A142personasles


gustaesto.Sel
primerodetus
amigos.

Search

http://androidcoffee.com/tutorialhowtodraw3dphotocubeinandroidstudio14/ 12/12

You might also like