【问题标题】:Calculate colours for points along an arbitrary gradient计算沿任意梯度的点的颜色
【发布时间】:2013-06-27 16:57:01
【问题描述】:

我正在尝试编写一个“应用渐变”函数,它采用一堆点和一个线性渐变并计算每个点的颜色。我有这样的东西(给定一个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 循环中的数学运算肯定不太正确——我需要使用三角函数来计算颜色吗?

【问题讨论】:

标签: c opengl gradient


【解决方案1】:

代替

// 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);
}

【讨论】:

  • 谢谢,这正是重新安排计算的重点。我还没有完全正确地绘制它,但这与我的形状点的布局以及 OpenGL 混合顶点的方式有关。
  • 做更多的测试——事实上,这实际上给了我一个径向渐变。
  • 啊,原来给了(破碎的)径向渐变。我的错误——我把这个答案设置为正确,因为我忘记指定我是在线性渐变之后。感谢您的意见。
猜你喜欢
  • 2014-08-21
  • 2018-04-18
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 2020-05-13
  • 1970-01-01
相关资源
最近更新 更多