锥形梯度在Qt(没有QConicalGradient)

Conical gradient in Qt (without QConicalGradient)

本文关键字:没有 QConicalGradient Qt      更新时间:2023-10-16

我必须在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

希望对你有帮助。