Game Development Reference

In-Depth Information

This will become the point of reference for the gradient, next we need to calculate the dis-

tance to the pixel x',y' using the Pythagorean theorem:

Finally we will normalize the distance by dividing it by the size of the image.

To compute the final color we need to consider that for each pixel we want to apply the

amount of the starting color as given by
r
and the inverse proportion of the ending color

amount (1 -
r)
, this ensures we blend just the right amount of each of the colors.

We can also reverse the gradient by doing the opposite calculation.

The linear gradient class derives from the gradient class and calculates the gradient data in

the constructor.

class gradient_linear : public gradient

{

public:

gradient_linear(unsigned int size, const color& startColor, const color& endColor, float angle, bool reverse=false)

: gradient(size, startColor, endColor, reverse)

, m_angle(angle)

{

m_data = new unsigned int[size*size];

const float angleSin = sinf(angle);

const float angleCos = cosf(angle);

for ( unsigned int y = 0; y < size; ++y ) {

for ( unsigned int x = 0; x < size; ++x ) {

float xx = x * angleSin;

float yy = y * angleCos;

float r = sqrtf(xx*xx + yy*yy) / size;

color c = reverse ? (startColor * (1-r)) + (endColor * (r)) : (startColor * r) + (endColor * (1 - r));