问题
I have created a rotating CUBE with the help of OPENGL in Android now i want to add a listener to handle the rotation of the cube i.e. When i click button then CUBE must start rotating and vice versa..How can i add a button on an OPENGL Screen?
回答1:
There are two options here:
- Create a layout that includes both your
GLSurfaceView
and whatever buttons/settings you want. Use the standardOnClickListener
for the button and have the listener call a method in your renderer to do the rotations. This is pretty much the easiest way to get this working, but the style of the button will change based on OS version and vendor. If you want to have more control over the button, you can try the other option. - Draw the button using OpenGL. After you render the cube, switch the projection matrix to an orthographic projection (
glOrtho
) with the same dimensions as your screen and draw a textured rectangle with your button image (You can also scale your button image like Android does by using 9 rectangles to keep the corners and edges sharp and just scale the inner part of the image which is usually a gradient or solid color). You'll have to set your renderer up to receive touch input and do a simple containment check that the pressed point is within the bounds of the button. If it is then you can call the method that handles rotation.
If you want a full-blown UI library, I'm sure there are several out there that exist for OpenGL ES on Android, and most of them would probably be part of larger game engines, which would handle most of the work for you. If you just want the single button though, I would recommend the first option as it's the simplest.
回答2:
You can draw a Button object (rectangle) which remains always perpendicular to the camera for the visual effect of a button. Everytime camera gets transformed the button object should also be relatively transformed.
The click part needs to be handled seperately thorough picking, i.e. you need to cast a ray from the centre of the camera and see if it intersects your 3D button object
Also if you were doing this on desktop you would have searched for "overlay GUI" libraries like CEGUI which is quite good http://www.cegui.org.uk/wiki/index.php/Main_Page or else you could also use Navilibrary and SDL http://princeofcode.com/navilibrary.php
In case of android you can explore the above libraries code (open source) and try to get the ideas from there.
来源:https://stackoverflow.com/questions/9075611/adding-button-on-an-opengl-screen