Creating a linear gradient in 2D array

前端 未结 4 1175
北海茫月
北海茫月 2021-02-06 13:05

I have a 2D bitmap-like array of let\'s say 500*500 values. I\'m trying to create a linear gradient on the array, so the resulting bitmap would look something like this (in gray

4条回答
  •  余生分开走
    2021-02-06 13:35

    I'll just post my solution.

    int ColourAt( int x, int y )
    {
      float imageX = (float)x / (float)BUFFER_WIDTH;
      float imageY = (float)y / (float)BUFFER_WIDTH;
    
      float xS = xStart / (float)BUFFER_WIDTH;
      float yS = yStart / (float)BUFFER_WIDTH;
      float xE = xEnd / (float)BUFFER_WIDTH;
      float yE = yEnd / (float)BUFFER_WIDTH;
      float xD = xE - xS;
      float yD = yE - yS;
    
      float mod = 1.0f / ( xD * xD + yD * yD );
    
      float gradPos = ( ( imageX - xS ) * xD + ( imageY - yS ) * yD ) * mod;
    
      float mag = gradPos > 0 ? gradPos < 1.0f ? gradPos : 1.0f : 0.0f;
    
      int colour = (int)( 255 * mag );
      colour |= ( colour << 16 ) + ( colour << 8 );
      return colour;
    }
    

    For speed ups, cache the derived "direction" values (hint: premultiply by the mag).

提交回复
热议问题