代码定义了一个
RGB
数据结构来表示颜色。
newRGB
函数根据其红色、绿色和蓝色分量创建并返回新的 RGB 颜色。
calcColor
函数接收RGB
结构的地址(colors
)、要生成的颜色总数(totalColors
)、正在计算的颜色的当前索引(currentIndex
)作为输入以及所需的颜色饱和度 (saturacao
) 和亮度 (brightness
)。该函数根据颜色在光谱中的索引以及指定的饱和度和亮度来计算颜色的 RGB 值。
在主函数中:
它计算并生成一系列波长的颜色,并将它们存储在颜色数组中。 它将颜色打印到屏幕上,每种颜色由两个字符表示 (
for example, " "
)。380
和 750
nm 之间的可见波长。如果用户输入-1,程序退出循环并终止。
但是,即使小于 481 的颜色也不会显示,并且在 750 之后,我继续收到高达 756 的颜色信息。
如何校准?
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <curses.h>
typedef struct {
int r;
int g;
int b;
} RGB;
RGB newRGB(int r, int g, int b) {
RGB color;
color.r = r;
color.g = g;
color.b = b;
return color;
}
void calcColor(RGB* colors, int totalColors, int currentIndex, float saturation, float luminosity);
int main() {
int totalColors = 60;
RGB colors[totalColors];
float saturation = 1.0;
float luminosity = 0.3;
initscr(); // Initialize curses mode
start_color(); // Initialize colors
int endColorIndex = totalColors - 18;
int startColorIndex = endColorIndex - 42;
for (int i = endColorIndex; i >= startColorIndex; i--) {
calcColor(&colors[i], totalColors, i, saturation, luminosity);
// Convert RGB colors to the curses standard model
int r = colors[i].r * 1000 / 255;
int g = colors[i].g * 1000 / 255;
int b = colors[i].b * 1000 / 255;
// Set the color in curses
init_color(i + 16, r, g, b); // need to define the color pair i+16
init_pair(i + 16, COLOR_BLACK, i + 16);
// Print the color
attron(COLOR_PAIR(i + 16)); // need to activate the color pair i+16
printw(" ");
attroff(COLOR_PAIR(i + 16));
}
// Loop to print colors on the screen
int wavelength;
while (1) {
// Ask the user for the visible wavelength
printw("\n\nEnter the visible wavelength (between 380 and 750 nm, or -1 to exit): ");
scanw("%d", &wavelength);
if (wavelength == -1) {
break; // Exit the loop if the user enters -1
}
// Calculate the position in the color array based on the wavelength
int index = (750 - wavelength) * (totalColors - 1) / (750 - 380);
// Print the corresponding color
printw("Corresponding Color: ");
attron(COLOR_PAIR(index + 16));
printw(" ");
attroff(COLOR_PAIR(index + 16));
refresh(); // Update the screen
}
getch(); // Wait for user input
endwin(); // End curses mode
return 0;
}
void calcColor(RGB* colors, int totalColors, int currentIndex, float saturation, float luminosity) {
float hue = currentIndex * (360.0 / totalColors);
float chroma = (1 - fabs(2 * luminosity - 1)) * saturation;
float x = chroma * (1 - fabs(fmod(hue / 60, 2) - 1));
float m = luminosity - chroma / 2;
float r, g, b;
if (hue >= 0 && hue < 60) {
r = chroma;
g = x;
b = 0;
} else if (hue >= 60 && hue < 120) {
r = x;
g = chroma;
b = 0;
} else if (hue >= 120 && hue < 180) {
r = 0;
g = chroma;
b = x;
} else if (hue >= 180 && hue < 240) {
r = 0;
g = x;
b = chroma;
} else if (hue >= 240 && hue < 300) {
r = x;
g = 0;
b = chroma;
} else {
r = chroma;
g = 0;
b = x;
}
colors->r = (r + m) * 255;
colors->g = (g + m) * 255;
colors->b = (b + m) * 255;
}