2010-08-02 63 views
10

我是一個新手,並嘗試使用OpenGL ES在我的iPhone屏幕上顯示一個精靈。 我知道它更簡單,更容易做到與cocos2d,但現在我試圖直接在OpenGL上編碼。 是否有任何簡單而有效的方式來加載和顯示OpenGL ES中的精靈。我到目前爲止發現的情況要複雜得多。 :(如何在用於iphone的OpenGL ES中加載和顯示圖像

+0

哪個版本的OpenGL ES,1或2? – 2010-08-02 11:14:45

+0

我正在使用ES 1. – nomann 2010-08-02 11:15:36

回答

15

下面是一些代碼從束加載PNG:

UIImage* image = [UIImage imageNamed:@"PictureName.png"]; 
GLubyte* imageData = malloc(image.size.width * image.size.height * 4); 
CGContextRef imageContext = CGBitmapContextCreate(imageData, image.size.width, image.size.height, 8, image.size.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast); 
CGContextDrawImage(imageContext, CGRectMake(0.0, 0.0, image.size.width, image.size.height), image.CGImage); 
CGContextRelease(imageContext); 

下面是一些代碼來創建與該圖像數據的紋理

GLuint texture; 
glGenTextures(1, &texture); 
glBindTexture(GL_TEXTURE_2D, texture); 
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.size.width, image.size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); 
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 

而如何的一個例子渲染:

glBindTexture(GL_TEXTURE_2D, texture); 
glVertexPointer(2, GL_FLOAT, 0, vertices); 
glNormalPointer(GL_FLOAT, 0, normals); 
glTexCoordPointer(2, GL_FLOAT, 0, textureCoords); 
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) 

在這裏,你需要找到適合你的頂點,法線和textureCoords的值需要。

更新1

一定要設置正確的狀態是這樣的:

glEnableClientState(GL_VERTEX_ARRAY); 
glEnableClientState(GL_NORMAL_ARRAY); 
glEnableClientState(GL_TEXTURE_COORD_ARRAY); 

如果使用glOrthof(見下文)在您的應用程序設置一個2D投影,您可以使用這些值:

GLfloat vertices[] = { 
    -1.0, 1.0, 
    1.0, 1.0, 
    -1.0, -1.0, 
    1.0, -1.0, }; 

GLfloat normals[] = { 
    0.0, 0.0, 1.0, 
    0.0, 0.0, 1.0, 
    0.0, 0.0, 1.0, 
    0.0, 0.0, 1.0 }; 

GLfloat textureCoords[] = { 
    0.0, 0.0, 
    1.0, 0.0, 
    0.0, 1.0, 
    1.0, 1.0 }; 

更新2

這是使用上面的代碼時呈現精靈怎麼坐在投影模式:

glMatrixMode(GL_PROJECTION); 
glLoadIdentity(); 
glOrthof(-5.0, 5.0, -7.5, 7.5, -1, 1); 
glMatrixMode(GL_MODELVIEW); 
glLoadIdentity(); 

這也是我怎麼設置我的混合功能。這允許在PNG文件中的透明度:

glEnable(GL_TEXTURE_2D); 
glEnable(GL_BLEND); 
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 
+0

Thnx 4 ur tym Martin。 我一定會嘗試。 :) – nomann 2010-08-02 11:32:56

+0

總是善於從任何花哨動畫之前的基礎開始......我也是全新的圖形/ iPhone的東西......好樣品。 – DRapp 2011-11-26 03:25:19

4

我建議看看蘋果的GLSprite示例應用程序。這正是這個應用程序所做的。

如果你想加載PVRTC壓縮紋理,請看他們的PVRTextureLoader例子。我使用我爲我的iPhone課寫的sample application中的代碼。

相關問題