Search code examples
opengl-esfillradial-gradients

(radial) gradient fill using OpenGL ES


I am currently drawing a shape using the following code;

GLfloat vertex = // vertex points

glLineWidth(2);

glEnableClientState(GL_VERTEX_ARRAY);
glColor4f(1.0, 0.0, 0.0, 1.0);
glVertexPointer(2, GL_FLOAT, 0, vertex);
glDrawArrays(GL_LINE_STRIP, 0, vertex_size);
glDisableClientState(GL_VERTEX_ARRAY);

The shape I draw closes itself, is it possible to fill this shape with a (radial) gradient? If so, how to go about doing this?


Solution

  • If you're in ES 1.x then you can't get a computed per-pixel radial gradient because colours are interpolated linearly across faces. So you can either upload a radial gradient texture or build suitable geometry to give a near-radial gradient.

    In ES 2.x there's no such restriction because you're defining what happens per-pixel for yourself. An extremely naive radial gradient fragment shader might be (coded extemporaneously, not thoroughly grammar checked):

    varying mediump vec3 myPosition;
    uniform mediump vec3 referencePosition;
    uniform lowp vec4 centreColour, outerColour;
    
    [...]
    
    mediump float distanceFromReferencePoint =
                           clamp(distance(myPosition, referencePosition), 0.0, 1.0);
    
    gl_FragColor = mix(centreColour, outerColour, distanceFromReferencePoint);