Graphics Reference
In-Depth Information
optimized in Core Animation; so if the thing you want to draw isn't a good match for any
of the standard layer classes, you will struggle to achieve good performance.
Because OpenGL makes no assumptions about your content, it can be blazingly fast. With
OpenGL, you can draw
anything you like
provided you know how to write the necessary
geometry and shader logic. This makes it a popular choice for games (where Core
Animation's limited repertoire of optimized content types doesn't always meet the
requirements), but it's generally overkill for applications with a conventional interface.
In iOS 5, Apple introduced a new framework called GLKit that takes away some of the
complexity of setting up an OpenGL drawing context by providing a
UIView
subclass
called
GLKView
that handles most of the setup and drawing for you. Prior to that it was
necessary to do all the low-level configuration of the various OpenGL drawing buffers
yourself using
CAEAGLLayer
, which is a
CALayer
subclass designed for displaying
arbitrary OpenGL graphics.
It is rare that you will need to manually set up a
CAEAGLLayer
any more (as opposed to
just using a
GLKView
), but let's give it a go for old time's sake. Specifically, we'll set up
an
OpenGL ES 2.0
context, which is the standard for all modern iOS devices.
Although it is possible to do this entirely without using GLKit, it involves a lot of
additional work in the form of setting up
vertex
and
fragment shaders
, which are self-
contained programs that are written in a C-like language called GLSL, and are loaded at
runtime into the graphics hardware. Writing GLSL code is not really related to the task of
setting up an
EAGLLayer
, so we'll use the
GLKBaseEffect
class to abstract away the
shader logic for us. Everything else, we'll do the old-fashioned way.
Before we begin, you need to add the GLKit and OpenGLES frameworks to your project.
You should then be able to implement the code in Listing 6.14, which does the bare
minimum necessary to set up a
GAEAGLLayer
with an OpenGL ES 2.0 drawing context
and render a colored triangle (see Figure 6.15).
Listing 6.14
Drawing a Triangle Using
CAEAGLLayer
#import
"ViewController.h"
#import
<QuartzCore/QuartzCore.h>
#import
<GLKit/GLKit.h>
@interface
ViewController
()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*glView;
@property
(
nonatomic
,
strong
)
EAGLContext
*glContext;
@property
(
nonatomic
,
strong
)
CAEAGLLayer
*glLayer;
@property
(
nonatomic
,
assign
)
GLuint
framebuffer;
@property
(
nonatomic
,
assign
)
GLuint
colorRenderbuffer;
@property
(
nonatomic
,
assign
)
GLint
framebufferWidth;
@property
(
nonatomic
,
assign
)
GLint
framebufferHeight;
@property
(
nonatomic
,
strong
)
GLKBaseEffect
*effect;