使用整数减法生成线性线渐变

时间:2018-07-02 13:56:09

标签: c++ colors line linear-gradients

我一直在破解此代码,试图使该参数线根据线的长度从洋红色到青色渐变(因此它不会被短线切断,或者也不会发生)很快就会出现),我正在尝试找出公式以查找要减去的内容,但是我似乎无法找出答案,有什么主意吗?

void ParametricLine(unsigned int _X1, unsigned int _Y1,
                unsigned int _X2, unsigned int _Y2)
{

    unsigned int lengthX;
    unsigned int lengthY;

    lengthX = abs((int)_X2 - (int)_X1);
    lengthY = abs((int)_Y2 - (int)_Y1);

    int longest;
    if (lengthX > lengthY)
    {
        longest = lengthX;
    }
    else
    {
        longest = lengthY;
    }

    unsigned int color = 16711935; //magenta is green 0, others 255
    unsigned int magenta = 16711935; //magenta is green 0, others 255

    unsigned int cyan = 65535;  //cyan is red = 0, G & B are 255
    //all 255 = 16777215

    unsigned int colorsubtract = (magenta - cyan)/longest;

    //MAGENTA: R: 255, G: 0,   B: 255
    //CYAN:    R:0,    G: 255, B: 255

    for (int i = 0; i < longest; i++)
    {
        float Ratio = (float)i / longest;

        unsigned int CurrY = LERP(_Y1, _Y2, Ratio);
        unsigned int CurrX = LERP(_X1, _X2, Ratio);
        /*color = LERP(16711935, 65535, longest/65535);*/
        if (color > cyan)
            color = color - colorsubtract;
        else if (color < cyan)
            color = cyan;

        //interpolate from magenta to cyan
        raster[Position(CurrX, floor(CurrY + 0.5))] = color;
    }
    raster[Position(_X1, _Y1)] = 16777215;
    raster[Position(_X2, _Y2)] = 16777215;
}

编辑:这是针对那些询问的Lerp函数-

unsigned int LERP(unsigned int _startval, unsigned int _endval, float _ratio){
return (((int)_endval - (int)_startval) * _ratio + (int)_startval);}

1 个答案:

答案 0 :(得分:0)

您在代码中做的事情很糟糕。如果要对线进行栅格化,最简单的方法是使用DDA algorithm(有时称为Bresenham算法),该方法不需要浮点算法,也不会多次绘制相同的点。

这里是another explanation,具有相同的概念。

这是yet another one,其中包括C代码。

阅读完所有提到的页面后,将颜色视为坐标之一,并对颜色应用完全相同的DDA算法。