Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing gradient background in OpenGL ES 2.0

I would like to make the background of my scene with gradient instead of a single color. Is it possible to do this? I am using OpenGL ES 2.0 on iOS.

like image 750
Erik Sapir Avatar asked Nov 20 '25 01:11

Erik Sapir


1 Answers

Ok, now again as an answer.

You can draw a rectangle that fills the entire screen and apply the gradient to it. To do that use the texture coordinates of the rectangles vertices to calculate the respective color in the vertex shader:

// ...
attribute vec2 textureCoordinate;
varying highp vec4 colorGradient;
// other attributes, uniforms, etc...

void main() {
    // This defines the colors of the 4 corners of your rectangle.
    // The gradient is then interpolated by the GPU between the vertices.
    colorGradient = vec4(textureCoordinate, 0.0f, 1.0f); // adjust as needed

    // ... set gl_Position, etc.
}

Now you can use the color in the fragment shader:

// ...
varying highp vec4 colorGradient;
// other uniforms, etc...

void main() {
    // do additional shading if needed

    // colorGradient is already interpolated between the vertices by the GPU
    gl_FragColor = colorGradient;
}

You can also use a varying vec3 and add the alpha channel later, but using a vec4 is a bit cleaner.

like image 170
Nero Avatar answered Nov 21 '25 15:11

Nero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!