计算沿任意梯度的点的颜色

标签 c opengl gradient

我正在尝试编写一个“应用渐变”函数,它采用一堆点和一个线性渐变并计算每个点的颜色。我有这样的东西(给定一个 points 数组和一个由两个点 startend 定义的渐变):

struct Colour {
    float red; float green; float blue;
};

struct Point {
    int x; int y;
    Colour colour;
};

Point points[total_points] = { ... };    
Point start = { ... };
Point end = { ... };

for (int i=0; i<total_points; i++) {

    // Get normalised position along x and y

    float scale_x = end.x-start.x;
    float pos_x = (scale_x == 0) ? 0 : (points[i].x-start.x) / scale_x;

    float scale_y = end.y-start.y;
    float pos_y = (scale_y == 0) ? 0 : (points[i].y-start.y) / scale_y;

    // Average the positions        
    float pos = .5 * (pos_x + pos_y);

    // Blend colours
    points[i].colour = blend_colour(start.colour, end.colour, pos);

}

我的颜色混合函数是这样简单的:

static Colour blend_colour(Colour start, Colour end, float position) {

    Colour blend;

    blend.red = (start.red * (1-position)) + (end.red * position);
    blend.green = (start.green * (1-position)) + (end.green * position);
    blend.blue = (start.blue * (1-position)) + (end.blue * position);

    return blend;

}

我在 for 循环中的数学肯定不太正确——我需要使用三角函数计算颜色吗?

最佳答案

代替

// Average the positions        
float pos = .5 * (pos_x + pos_y);

尝试

// Get scaled distance to point by calculating hypotenuse
float dist = sqrt(pos_x*pos_x + pos_y*pos_y);

此外,虽然编译器会为您完成,但您应该将比例因子提升到循环之外。 事实上,计算距离的比例因子可能会更好:

Point start = { ... };
Point end = { ... };

float xdelta = end.x - start.x;
float ydelta = end.y - start.y;
float hypot = sqrt(xdelta*xdelta + ydelta*ydelta);

for (int i=0; i<total_points; i++) {

    // Get normalised distance to points[i]

    xdelta = points[i].x - start.x;
    ydelta = points[i].y - start.y;
    float dist = sqrt(xdelta*xdelta + ydelta*ydelta);
    if (hypot) dist /= hypot;

    // Blend colours 
    points[i].colour = blend_colour(start.colour, end.colour, dist);
}

关于计算沿任意梯度的点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17338292/

相关文章:

c++ - OpenGL/C++ : Back to Front rendering with vertex buffers

opengl - 是否可以在内存表面上绘制 OpenGL?

CSS3 白色到透明渐变

c - C 中推箱子游戏加载程序的段错误

使用 void(*)(void) 指针调用 void function(int) 并准备使用参数堆栈

c++ - 如何使用 FREEGLUT 获得多显示器的所有支持分辨率?

ios - 根据单元格索引路径向 TableView 单元格元素添加渐变层

c - 传递 'unpack_code' 参数 3 时的指针目标符号性不同 [-Wpointer-sign],如何解决这个问题?

c - 是否包含头文件

python - 使用 python 将高程 (XYZ) 数据转换为坡度/梯度图