How can I place a UILabel within an OpenGL ES 2.0 application?
I have an OpenGL ES 2.0 application for iPad. Is it possible to place text on the screen using a UILabel, like you can in a traditional iOS application?
I tried inserting a label, but it didn't show up. If it is possible, can someone explain the process? Should we insert the label in the v开发者_C百科iewcontroller.xib file or the mainwindow.xib file, and also where must the appropriate code be written?
As I explain in my similar answers here and here, your OpenGL ES content is hosted within a CAEAGLLayer that backs a particular UIView. This UIView behaves like any other view in the display hierarchy, so you can add UILabels and other controls on top of it or as siblings that overlay this view.
If you are using Interface Builder to lay out your UI, you should have a view that contains your OpenGL ES content somewhere in that interface. You can add the UILabel as a subview of this UIView in Interface Builder and have it show (remember to color the text appropriately so that you don't get black text on a black OpenGL ES background). You can also do this programmatically by using -addSubview:
on your OpenGL ES hosting view.
In my tests, overlaying UIKit controls on OpenGL ES content only leads to a slight reduction in rendering speed (from 1-5% in my applications), so this is a viable approach.
If you want to see an example of this in action, look at the source code for my Molecules application, which uses labels and other controls overlaid on the OpenGL ES content on the iPhone.
Only do that if the labels go on top of the OpenGL content. UIKit elements sometimes do not mix well with OpenGL elements. Blending OpenGL content with transparency on top of UIKit elements is really slow. In these cases, it's better to add the label in your OpenGL code. Static text is very easy, just draw a flat object facing the camera and with a texture image of your text. Dynamic text would require more work to adjust the texture with the font to show the correct text.
To do this, add the label to to viewcontroller.xib file, not the mainwindow.xib file. The appropriate code for controlling the UILabel would go in the view controller's .h and .m files. In the standard Xcode iOS OpenGL ES Application template the main view controller's .xib file will contain one EAGLView view. The label can be added to that view, and connected to an IBOutlet in the view controller's .h file.
精彩评论