如何在由颜色数组表示的精灵上绘制像素线?
How to draw a pixel line on a sprite represented by an array of color?
我正在制作自己的图形库,我有一个 Sprite class,它只是一组具有宽度和高度的颜色。我可以通过更改其颜色值来设置精灵上的像素。如何在给定起始位置和结束位置的精灵上画一条线?
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;
};
使用类似于 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;
}
}
}
我正在制作自己的图形库,我有一个 Sprite class,它只是一组具有宽度和高度的颜色。我可以通过更改其颜色值来设置精灵上的像素。如何在给定起始位置和结束位置的精灵上画一条线?
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;
};
使用类似于 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;
}
}
}