Search code examples
c++linespritedrawpixel

How to draw a pixel line on a sprite represented by an array of color?


I'm making my own graphics library and I have a Sprite class which is just an array of colors with a width and a height. I can set a pixel on the sprite by changing its color value. How can I draw a line on a sprite given a start position and an end position?

class Sprite
{
public:
    Sprite();

public:
    LongUtils::Pixel GetPixel(int32_t x, int32_t y) const;
    bool  SetPixel(int32_t x, int32_t y, Pixel p);
    LongUtils::Pixel* GetData(); // return the *data
    LongUtils::Pixel* GetBlockData(uint32_t x, uint32_t y, uint32_t w, uint32_t h);

private:
    LongUtils::Pixel* data = nullptr;
    int32_t width = 0;
    int32_t height = 0;
};

Solution

  • Use something like Bresenham's line algorithm. Here's an example:

    void Line( float x1, float y1, float x2, float y2, const Color& color )
    {
            // Bresenham's line algorithm
      const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
      if(steep)
      {
        std::swap(x1, y1);
        std::swap(x2, y2);
      }
     
      if(x1 > x2)
      {
        std::swap(x1, x2);
        std::swap(y1, y2);
      }
     
      const float dx = x2 - x1;
      const float dy = fabs(y2 - y1);
     
      float error = dx / 2.0f;
      const int ystep = (y1 < y2) ? 1 : -1;
      int y = (int)y1;
     
      const int maxX = (int)x2;
     
      for(int x=(int)x1; x<=maxX; x++)
      {
        if(steep)
        {
            SetPixel(y,x, color);
        }
        else
        {
            SetPixel(x,y, color);
        }
     
        error -= dy;
        if(error < 0)
        {
            y += ystep;
            error += dx;
        }
      }
    }