【问题标题】:Opengl 2.0 glColor4f not workingOpengl 2.0 glColor4f 不工作
【发布时间】:2014-05-21 21:22:58
【问题描述】:

我正在使用 GLKit 创建一个视图以在 iOS 中试验 opengl。视图有如下加载方式:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    if (!self.context) {
        NSLog(@"Failed to create ES context");
    }

    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

    [EAGLContext setCurrentContext:self.context];
    self.effect = [[GLKBaseEffect alloc] init];

}

在一个形状的绘制方法中,我有以下代码:

float vertices[] = {
    -1, -1,
    1, -1,
    0,  1};

glEnableVertexAttribArray(GLKVertexAttribPosition);

glColor4f(0.0, 1.0, 0.0, 1.0);
glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glDrawArrays(GL_TRIANGLES, 0, sizeof(vertices));

glDisableVertexAttribArray(GLKVertexAttribPosition);

此代码将在屏幕中心绘制一个三角形,但该三角形是白色的。我用glColor4f(0.0, 1.0, 0.0, 1.0) 将当前颜色设置为绿色,但这不会改变当前的绘图颜色。如何更改三角形的颜色?

【问题讨论】:

    标签: ios opengl-es glkit


    【解决方案1】:

    OpenGL 2.0 使用着色器来光栅化几何体。你需要告诉你的着色器你想看到什么颜色。这样做的方法通常是将顶点的颜色属性设置为您想要的,我没有使用过 GLKit 但我看到它有一个GLKVertexAttribColor。尝试将其设置为您想要的颜色:

    GLfloat triangle_colors[] = {
        1.0, 1.0, 0.0, 1.0,
        0.0, 0.0, 1.0, 1.0,
        1.0, 0.0, 0.0, 1.0,
    };
    
    glVertexAttribPointer(
        GLKVertexAttribColor, // attribute
        4,                 // number of elements per vertex, here (r,g,b,a
        GL_FLOAT,          // the type of each element
        GL_FALSE,          // take our values as-is
        0,                 // no extra data between each position
        triangle_colors
    );
    

    【讨论】:

      【解决方案2】:

      glColor4f 不是 ES 2.0 调用。你必须拉入一个 ES 1.0 头文件才能编译它。

      如果您只想使用纯色,最简单的方法是在着色器中定义一个uniform 变量,然后将您的颜色作为制服传递。或者你可以让颜色成为一个额外的顶点属性。

      如果您使用的是 GLKit 提供的预烘焙着色器,您应该能够使用 GLKVertexAttribColor 传递颜色,这与使用 GLKVertexAttribPosition 指定顶点位置的方式非常相似。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多