2013-03-11 71 views
1

我必須在Qt C++中繪製圓錐漸變,但我無法使用QConicalGradient。我確實有一個線性漸變,但我不知道如何製作一個圓錐漸變。我不想完成代碼,但我要求一個簡單的算法。Qt中的圓錐漸變(不含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; 
    } 
} 

你能幫助我嗎?

+0

*爲什麼*你不能使用'QConicalGradient'? – ecatmur 2013-03-11 17:21:53

+0

因爲我們必須實現您自己的繪圖圓錐漸變版本 – 2013-03-11 17:56:20

回答

1

下面是一些僞代碼:

鑑於一些地區油漆,併爲您的梯度定義的中心......

對於您在區域畫上的每個點,計算角度到你的漸變的中心。

// 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

希望有所幫助。

+0

我不知道我必須在這一行做什麼:float hue = map(-PI,angle,PI,0,255); 我在下面粘貼了我的代碼。 – 2013-03-12 19:54:14