In this application we will see how to create texture from an image. We are using here OpenGL ES to create a texture from the image data. So let see how it will be worked.
Step 1: Create a Window base application using template. Give the application name “OpenGL”.
Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.
Step 3: We need to add here UIView class to the project.Choose New file -> Select cocoa touch classes group and then select UIView subclass. Give the name “OpenGLView”.
Step 4: We need to add the resource file called as “Sprite-2.png” into the resource folder. Select resources and add files existing sources and select the Sprite-2.png.
Step 5: In the OpenGLAppDelegate.h file, we have added OpenGLView class. So make the following changes.
@interface OpenGLAppDelegate : NSObject {
UIWindow *window;
IBOutlet OpenGLView *glView;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
Step 6: Open the OpenGLAppDelegate.m file and make the following changes in the file:
{
[glView startAnimation];
}
- (void) applicationWillResignActive:(UIApplication *)application
{
[glView stopAnimation];
}
- (void) applicationDidBecomeActive:(UIApplication *)application
{
[glView startAnimation];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[glView stopAnimation];
}
Step 7: We need to add two framework in the application, one OpenGLES.framework and another QuartzCore.framework. Framework path is:
System->developer->platform->iPhone Simulator->developer->SDKs-> iPhoneSimulator 2.2 sdk->System->Library->Frameworks.
Step 8: Open the OpenGLView.h file. and define backing height, width, renderbuffer and framebuffers used to render to the view. So make the following changes in the file:
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
@interface OpenGLView : UIView
{
@private
GLint backingWidth;
GLint backingHeight;
EAGLContext *context;
GLuint viewRenderbuffer, viewFramebuffer;
GLuint depthRenderbuffer;
GLuint spriteTexture;
BOOL animating;
BOOL displayLinkSupported;
NSInteger animationFrameInterval;
id displayLink;
NSTimer *animationTimer;
}
@property (readonly, nonatomic, getter=isAnimating) BOOL animating;
@property (nonatomic) NSInteger animationFrameInterval;
- (void)startAnimation;
- (void)stopAnimation;
- (void)drawView;
Step 9: Double click your MainWindow.xib file and open it to the Interface Builder. Open the window, drag view from the library and place it to the window. Select the View from the main window and bring up Identity Inspector, change the class name into the OpenGLView. Select OpenGLAppDelegate icon from the main window, bring up connection inspector and drag from the glView to the OpenGLView. Now save it, close it and go back to the Xcode.
Step 10: Make the following changes in the OpenGlView.m file.
#import <OpenGLES/EAGLDrawable.h>
- (id)initWithCoder:(NSCoder*)coder
{
if((self = [super initWithCoder:coder])) {
CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer;
eaglLayer.opaque = YES;
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
if(!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer])
{
[self release];
return nil;
}
animating = FALSE;
displayLinkSupported = FALSE;
animationFrameInterval = 1;
displayLink = nil;
animationTimer = nil;
NSString *reqSysVer = @"3.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
displayLinkSupported = TRUE;
[self setupView];
[self drawView];
}
return self;
}
- (BOOL)createFramebuffer
{
glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
return NO;
}
return YES;
}
- (void) startAnimation
{
if (!animating)
{
if (displayLinkSupported)
{
displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(drawView)];
[displayLink setFrameInterval:animationFrameInterval];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
else
animationTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)((1.0 / 60.0) * animationFrameInterval) target:self selector:@selector(drawView) userInfo:nil repeats:TRUE];
animating = TRUE;
}
}
- (void)stopAnimation
{
if (animating)
{
if (displayLinkSupported)
{
[displayLink invalidate];
displayLink = nil;
}
else
{
[animationTimer invalidate];
animationTimer = nil;
}
animating = FALSE;
}
}
- (void)setupView
{
CGImageRef spriteImage;
CGContextRef spriteContext;
GLubyte *spriteData;
size_t width, height;
glViewport(0, 0, backingWidth, backingHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glVertexPointer(2, GL_FLOAT, 0, spriteVertices);
glEnableClientState(GL_VERTEX_ARRAY);
glTexCoordPointer(2, GL_SHORT, 0, spriteTexcoords);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
spriteImage = [UIImage imageNamed:@"Sprite-2.png"].CGImage;
width = CGImageGetWidth(spriteImage);
height = CGImageGetHeight(spriteImage);
if(spriteImage) {
spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width * 4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), spriteImage);
CGContextRelease(spriteContext);
glGenTextures(1, &spriteTexture);
glBindTexture(GL_TEXTURE_2D, spriteTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
free(spriteData);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
}
}
Step 11: Now compile and run the application in the Simulator.
You can downloaded SourceCode from here OpenGL 2












hi, thanks to publish a tutorial like this one, but it doesn’t work… I just started dubbing it but I found too many errors, beginning from a lot of missing imports, spriteVertices never initialized, no Sprite-2.png added to the article, … I hope you will correct (or update it) in the near future because a simple code with a a great output like yours is a plus. With best regards, davide
First of all thanks for the tutorial, but unfortunately the decoding of the sprite texture is failing in the sample code given above.
Problem solved :
Add this line after the getting width.
// Get the width and height of the image
width = CGImageGetWidth(spriteImage);
height= CGImageGetHeight(spriteImage); –> This was missing….
I have added the code into code.. Please check it..
Thx, still not checked on this one. Just wanted to say this is one of the best iphone programming tutorial sites. Thx for that.