首页 > 解决方案 > 如何在由颜色数组表示的精灵上绘制像素线?

问题描述

我正在制作自己的图形库,并且我有一个 Sprite 类,它只是一个具有宽度和高度的颜色数组。我可以通过改变它的颜色值在精灵上设置一个像素。如何在给定开始位置和结束位置的精灵上画一条线?

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;
};

标签: c++linespritedrawpixel

解决方案


使用类似 Bresenham 的线算法。这是一个例子:

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;
    }
  }
}

推荐阅读