编程彩虹c语言,c – 如何渲染彩虹光谱?

这段代码展示了如何根据波长创建彩虹效果,基于HSL颜色表示法。通过迭代色调并调整强度,实现了从380nm到780nm的可见光谱的颜色映射。代码中还包含了一个 RainbowLabel 类,用于自适应窗口大小显示彩虹图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你需要

read this paper.说真的.

除此之外,它可以采用的是使用QColor :: fromHslF(x / * 0.8,0.95,0.5)迭代HSL颜色表示中的色调,其中x在彩虹上从0.0变化到1.0.它根本不是物理上准确的,但也许它会这样做.

否则,您需要一个稍微复杂的代码,它非常简单地接近上面引用的论文.

#include

#include

#include

#include

#include

#include

QColor wavelengthToColor(qreal lambda)

{

// Based on: http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm

// The foregoing is based on: http://www.midnightkite.com/color.html

struct Color {

qreal c[3];

QColor toColor(qreal factor) const {

qreal const gamma = 0.8;

int ci[3];

for (int i = 0; i < 3; ++i) {

ci[i] = c[i] == 0.0 ? 0.0 : qRound(255 * pow(c[i] * factor,gamma));

}

return QColor(ci[0],ci[1],ci[2]);

}

} color;

qreal factor = 0.0;

static qreal thresholds[] = { 380,440,490,510,580,645,780 };

for (unsigned int i = 0; i < sizeof(thresholds)/sizeof(thresholds[0]); ++ i) {

using std::swap;

qreal t1 = thresholds[i],t2 = thresholds[i+1];

if (lambda < t1 || lambda >= t2) continue;

if (i%2) swap(t1,t2);

color.c[i % 3] = (i < 5) ? (lambda - t2) / (t1-t2) : 0.0;;

color.c[2-i/2] = 1.0;

factor = 1.0;

break;

}

// Let the intensity fall off near the vision limits

if (lambda >= 380 && lambda < 420) {

factor = 0.3 + 0.7*(lambda-380) / (420 - 380);

}

else if (lambda >= 700 && lambda < 780) {

factor = 0.3 + 0.7*(780 - lambda) / (780 - 700);

}

return color.toColor(factor);

}

QPixmap rainbow(int w,int h)

{

QPixmap pm(w,h);

QPainter p(&pm);

qreal f1 = 1.0/400;

qreal f2 = 1.0/780;

for (int x = 0; x < w; ++ x) {

// Iterate across frequencies,not wavelengths

qreal lambda = 1.0/(f1-(x/qreal(w)*(f1-f2)));

p.setPen(wavelengthToColor(lambda));

p.drawLine(x,x,h);

}

return pm;

}

class RainbowLabel : public QLabel {

protected:

void resizeEvent(QResizeEvent *) {

setPixmap(rainbow(width(),height()));

}

};

int main(int argc,char *argv[])

{

QApplication a(argc,argv);

RainbowLabel l;

l.resize(600,100);

l.show();

return a.exec();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值