我开始做“生命游戏”,我想,如果我能有比1或0更多的状态呢?
但我需要不同的颜色。我希望将颜色链接到网格/对象(网格是一个类)。
什么是一个好的/体面的方式存储彩色托盘快速/容易访问?
我目前不太理想的解决方案是,每个红色、绿色、蓝色和alpha值都有4个指向内存的指针。
在我的类中,我有一个函数将值v的颜色设置为rgba:
SetColor(v, r, g, b, a) //Set v to the appropriate color values我想保持这个功能很容易修改一个颜色。
发布于 2016-09-23 14:00:33
我用的是一些非常简单的东西:4只浮标
struct Color {
float r, g, b, a;
};然后,你可以得到类似于彩色托盘的东西:
// a Palette of 8 colors:
using palette_t = std::array<Color, 8>
palette_t myPalette { /* ... */ };然后,在网格或对象类中,可以使用索引引用颜色:
struct Grid {
// lot's of code
private:
std::size_t colorIndex = 0;
};但随后您询问了如何轻松地访问颜色(我猜容易访问来自于Grid类)
有很多解决方案可以存在,而且大多数将取决于您的项目结构。这是许多其他人的一个想法。我希望它能激励你。
您可以存储返回正确颜色的函数:
struct Grid {
// lot's of code
private:
std::size_t colorIndex = 0;
std::function<Color(std::size_t)> color;
};然后,正确地创建网格:
struct GridCreator {
GridCreator(const palette_t& aPalette) : palette{aPalette} {}
Grid create(std::size_t color) const {
Grid grid;
// create the grid
grid.color = [this](std::size_t index) {
return palette[index];
};
return grid;
}
private:
const palette_t& palette;
};然后,您可以在不直接知道调色板存在于Grid类的情况下免费访问您的调色板。
发布于 2016-09-23 13:56:51
有一系列的颜色:
std::vector<std::array<unsigned char, 4>> palette {
{255, 0, 0, 255}, // red
{0, 255, 0, 255}, // green
{0, 0, 255, 255}, // blue
};然后,对于每个字段,将索引存储在数组中(类型为size_t)。示例:
auto id = field[5][2];
auto color = palette[id];
auto r = color[0], alpha = color[3];更改颜色非常简单,如:
palette[id] = {255, 0, 0, 127};若要添加新颜色,请使用:
palette.push_back({255, 0, 0, 127}).或者,您可以定义一个简单的结构,以便您可以使用color.r、color.alpha等,并编写一个构造函数以方便颜色创建。
请注意,此示例是C++11代码。
发布于 2016-09-23 13:46:44
Enum是颜色结构的完美选择。
为了你的特殊情况。您可以将每个点的颜色存储为单个整数。
uint32_t point_color = field[5][2].color;
unsigned char* color = (unsigned char*)point_color[id];
auto r = color[0], alpha = color[3];
/////
void SetColor(uint32_t& point_color,unsigned char r,
unsigned char g,unsigned char b,unsigned char a){
point_color=r | (b*(1<<8)) | (g*(1<<16)) | (a*(1<<24));
}这种结构的优点
https://stackoverflow.com/questions/39662339
复制相似问题