c++ - 如何在由颜色数组表示的精灵上绘制像素线?
问题描述
我正在制作自己的图形库,并且我有一个 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;
};
解决方案
使用类似 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;
}
}
}
推荐阅读
- lua - 为什么 Roblox 和 Roblox Studio 在运行某些没有错误代码的脚本时都会崩溃?
- python - val, idx = min((val, idx) for (idx, val) in enumerate(my_list)) 是如何工作的?
- karate - 空手道 driver.url 不捕获窗口位置中的内容
- jquery - 如何使用 JQuery 创建相同数量的输入字段并从可用列表项中获取数据?
- python - 如何防止我的机器人获得角色
- angular - Angular mat-tab:仅加载初始选定选项卡的内容
- c# - 如何使用'LibGit2sharp'获取有关每个提交的git分支信息
- mongodb - 如何在 macbook 上运行 mongo 导出?
- c# - C# - Unity - 参数传递问题
- angular - npm 版本只是主要的(没有次要/补丁部分)