@@ -827,16 +827,27 @@ Image GenImageGradientLinear(int width, int height, int direction, Color start,
827827 float cosDir = cosf (radianDirection );
828828 float sinDir = sinf (radianDirection );
829829
830+ // Calculate how far the top-left pixel is along the gradient direction from the center of said gradient
831+ float startingPos = 0.5 - (cosDir * width /2 ) - (sinDir * height /2 );
832+ // With directions that lie in the first or third quadrant (i.e. from top-left to
833+ // bottom-right or vice-versa), pixel (0, 0) is the farthest point on the gradient
834+ // (i.e. the pixel which should become one of the gradient's ends color); while for
835+ // directions that lie in the second or fourth quadrant, that point is pixel (width, 0).
836+ float maxPosValue =
837+ ((signbit (sinDir ) != 0 ) == (signbit (cosDir ) != 0 ))
838+ ? fabs (startingPos )
839+ : fabs (startingPos + width * cosDir );
830840 for (int i = 0 ; i < width ; i ++ )
831841 {
832842 for (int j = 0 ; j < height ; j ++ )
833843 {
834844 // Calculate the relative position of the pixel along the gradient direction
835- float pos = (i * cosDir + j * sinDir )/( width * cosDir + height * sinDir );
845+ float pos = (startingPos + ( i * cosDir + j * sinDir )) / maxPosValue ;
836846
837847 float factor = pos ;
838- factor = (factor > 1.0f )? 1.0f : factor ; // Clamp to [0,1]
839- factor = (factor < 0.0f )? 0.0f : factor ; // Clamp to [0,1]
848+ factor = (factor > 1.0f )? 1.0f : factor ; // Clamp to [-1,1]
849+ factor = (factor < -1.0f )? -1.0f : factor ; // Clamp to [-1,1]
850+ factor = factor / 2 + 0.5f ;
840851
841852 // Generate the color for this pixel
842853 pixels [j * width + i ].r = (int )((float )end .r * factor + (float )start .r * (1.0f - factor ));
0 commit comments