我必须在 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
对象与您正在使用的QPainter
或QBrush
或QPen
一起使用。或者,如果您将 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/