这是我用来加载纹理的代码.图像是CGImageRef.使用此代码加载图像后,我最终使用glDrawArrays()绘制图像.
size_t imageW = CGImageGetWidth(image);
size_t imageH = CGImageGetHeight(image);
size_t picSize = pow2roundup((imageW > imageH) ? imageW : imageH);
GLubyte *textureData = (GLubyte *) malloc(picSize * picSize << 2);
CGContextRef imageContext = CGBitmapContextCreate( textureData, picSize, picSize, 8, picSize << 2, CGImageGetColorSpace(image), kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big );
if (imageContext != NULL) {
CGContextDrawImage(imageContext, CGRectMake(0.0, 0.0, (CGFloat)imageW, (CGFloat)imageH), image);
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// when texture area is large, bilinear filter the original
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// the texture wraps over at the edges (repeat)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picSize, picSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
GLenum err = glGetError();
if (err != GL_NO_ERROR)
NSLog(@"Error uploading texture. glError: 0x%04X", err);
CGContextRelease(imageContext);
}
free(textureData);
Run Code Online (Sandbox Code Playgroud)
当图像为320x480时,这似乎工作正常,但是当图像较大时它会失败(例如,picSize = 2048).
这是我在调试器控制台中得到的:
Error uploading texture. glError: 0x0501
Run Code Online (Sandbox Code Playgroud)
这个错误是什么意思?什么是最好的解决方法?
你不是只是达到最大纹理大小限制?错误代码是GL_INVALID_VALUE,请参阅glTexImage2D文档:
GL_INVALID_VALUE如果width或height小于0或大于2 + GL_MAX_TEXTURE_SIZE,或者如果不能表示2k+2(border)某个整数值,则生成k.
iPhone不支持大于1024像素的纹理.解决方法是将图像拆分为多个纹理.