c++ - Qt 中的圆锥形渐变(不带 QConicalGradient)

标签 c++ qt graph-algorithm

我必须在 Qt C++ 中绘制圆锥形渐变,但我无法使用 QConicalGradient。我确实有一个线性渐变,但我不知道如何制作锥形渐变。我不想要完整的代码,但我想要一个简单的算法。


for(int y = 0; y < image.height(); y++){
    QRgb *line = (QRgb *)image.scanLine(y);

    for(int x = 0; x < image.width(); x++){
        QPoint currentPoint(x, y);
        QPoint relativeToCenter = currentPoint - centerPoint;
        float angle = atan2(relativeToCenter.y(), relativeToCenter.x);
        // I have a problem in this line because I don't know how to set a color:
        float hue = map(-M_PI, angle, M_PI, 0, 255);
        line[x] = (red << 16) + (grn << 8) + blue;
    }
}

你能帮我吗?

最佳答案

这是一些伪代码:

给定一些要绘制的区域,以及定义的渐变中心......

对于区域中要绘制的每个点,计算与渐变中心的角度。

// QPoint currentPoint;  // created/populated with a x, y value by two for loops
QPoint relativeToCenter = currentPoint - centerPoint;
angle = atan2(relativeToCenter.y(), relativeToCenter.x());

然后使用线性渐变或某种映射函数将该角度映射到颜色。

float hue = map(-PI, angle, PI, 0, 255); // convert angle in radians to value
// between 0 and 255

绘制该像素,并对您所在区域中的每个像素重复。

编辑:根据渐变的图案,您将需要创建不同的QColor像素。例如,如果您有一个“彩虹”渐变,只是从一种色调到下一种色调,您可以使用如下线性映射函数:

float map(float x1, float x, float x2, float y1, float y2)
{
     if(true){
          if(x<x1)
                x = x1;
          if(x>x2)
                x = x2;
     }

     return y1 + (y2-y1)/(x2-x1)*(x-x1);
}

然后使用输出值创建一个 QColor 对象:

float hue = map(-PI, angle, PI, 0, 255); // convert angle in radians to value
// between 0 and 255
QColor c;
c.setHsl( (int) hue, 255, 255);

然后将此QColor对象与您正在使用的QPainterQBrushQPen一起使用。或者,如果您将 qRgb 值放回:

line[x] = c.rgb();

http://qt-project.org/doc/qt-4.8/qcolor.html

希望有帮助。

关于c++ - Qt 中的圆锥形渐变(不带 QConicalGradient),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15344163/

相关文章:

c++ - 使用 automake 和 autoconf 安装 C++ 程序

c++ - 初始化列表没有合适的默认构造函数可用错误

algorithm - 如何将无向图转换为没有循环的有向图(Directed acyclic graph)

c++ - 类(class)成员指向类(class)成员

c++ - 如何从模板特化中找到重复的定义?

c++ - 在主窗口之前显示对话框

c++ - Qt: close, destroy 和 delete later 有什么区别?

c++ - 如何使用OpenGL渲染到一个QMainWindow的两个QWidget?

algorithm - 有两个目标的最短路径

algorithm - 为什么找到最大切割 NP-hard?