我刚开始在 iOS 上使用 openGLES2.0,我正在尝试在屏幕上渲染纹理。
问题是纹理看起来与它应该渲染的真实图像不同(暗淡且几乎是单色的)。从某种意义上说,纹理图像的真实颜色在使用 openGL 进行渲染时并没有反映出来
着色器程序非常简单:
片段着色器
varying lowp vec4 DestinationColor;
varying lowp vec2 TexCoordOut;
uniform sampler2D Texture;
void main(void) {
gl_FragColor = texture2D(Texture, TexCoordOut);
}
顶点着色器
attribute vec4 Position;
uniform mat4 Projection;
uniform mat4 Modelview;
attribute vec2 TexCoordIn;
varying vec2 TexCoordOut;
void main(void) {
gl_Position = Projection * Modelview * Position;
TexCoordOut = TexCoordIn;
}
相同的纹理在 openGL ES 1.0 上运行良好,颜色显示正确!
编辑:
OpenGL上下文设置代码:
- (void)setupContext {
EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
_context = [[EAGLContext alloc] initWithAPI:api];
if (!_context) {
DLog(@"Failed to initialize OpenGLES 2.0 context");
exit(1);
}
if (![EAGLContext setCurrentContext:_context]) {
DLog(@"Failed to set current OpenGL context");
exit(1);
}
}
纹理加载代码:
- (GLuint)setupTexture:(UIImage *)image {
glGenTextures(1, &Texture1);
glBindTexture(GL_TEXTURE_2D, Texture1);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
GLuint width = CGImageGetWidth(image.CGImage);
GLuint height = CGImageGetHeight(image.CGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
void *imageData = malloc( height * width * 4 );
CGContextRef imgContext = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
CGContextTranslateCTM (imgContext, 0, height);
CGContextScaleCTM (imgContext, 1.0, -1.0);
CGContextSetBlendMode(imgContext, kCGBlendModeCopy);
CGColorSpaceRelease( colorSpace );
CGContextClearRect( imgContext, CGRectMake( 0, 0, width, height ) );
CGContextTranslateCTM( imgContext, 0, height - height );
CGContextDrawImage( imgContext, CGRectMake( 0, 0, width, height ), image.CGImage );
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
CGContextRelease(imgContext);
free(imageData);
return Texture1;
}
第二次编辑:图层设置
- (void)setupLayer {
_eaglLayer = (CAEAGLLayer*) self.layer;
_eaglLayer.opaque = YES;
_eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
}
我已将这段代码添加到图层设置中。还是没有运气!