从渐变中获得中间颜色

Nar*_*rek 5 c++ qt gradient colors linear-gradients

说我有一个线性渐变,如图所示:

QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, 100));
linearGrad.setColorAt(1, Qt::red);
linearGrad.setColorAt(0.5, Qt::yellow);
linearGrad.setColorAt(0, Qt::green);
Run Code Online (Sandbox Code Playgroud)

如何获得此渐变中的点QPointF(0,28.5)的颜色?

实际上,我希望具有这种颜色分布,以便能够选择中间颜色。我不在乎是否通过使用QLinearGradient或其他方法完成。

azf*_*azf 6

张梅森的回答确实有效,而且非常好!让 controlPoints() 返回 a QMap<qreal,QColor>,键值在 0.0 到 1.0 之间。这就是我的做法(感谢张梅森)

QColor getColor(qreal key) const
{
    // key must belong to [0,1]
    key = Clip(key, 0.0, 1.0) ;

    // directly get color if known
    if(controlPoints().contains(key))
    {
        return controlPoints().value(key) ;
    }

    // else, emulate a linear gradient
    QPropertyAnimation interpolator ;
    const qreal granularite = 100.0 ;
    interpolator.setEasingCurve(QEasingCurve::Linear) ;
    interpolator.setDuration(granularite) ;
    foreach( qreal key, controlPoints().keys() )
    {
        interpolator.setKeyValueAt(key, controlPoints().value(key)) ;
    }
    interpolator.setCurrentTime(key*granularite) ;
    return interpolator.currentValue().value<QColor>() ;
}
Run Code Online (Sandbox Code Playgroud)


use*_*395 5

我将渐变颜色存储在一个QList中,然后使用颜色插值进行计算。

QColor ColorGradient::getColor(double value)
{
  qDebug()<< "ColorGradient::getColor:";
    //Asume mGradientColors.count()>1 and value=[0,1]
    double stepbase = 1.0/(mGradientColors.count()-1);
    int interval=mGradientColors.count()-1; //to fix 1<=0.99999999;

      for (int i=1; i<mGradientColors.count();i++)//remove begin and end
        {
            if(value<=i*stepbase ){interval=i;break;}
        }
       double percentage = (value-stepbase*(interval-1))/stepbase;
       QColor color(interpolate(mGradientColors[interval],mGradientColors[interval-1],percentage));        
       return color;
}
QColor ColorGradient::interpolate(QColor start,QColor end,double ratio)
{
    int r = (int)(ratio*start.red() + (1-ratio)*end.red());
    int g = (int)(ratio*start.green() + (1-ratio)*end.green());
    int b = (int)(ratio*start.blue() + (1-ratio)*end.blue());
    return QColor::fromRgb(r,g,b);
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是一个很好的答案。对于像我这样搜索的其他人,我发现它比公认的答案更有帮助。 (3认同)

Pie*_*esu 3

只有一个方法可以做到:

QPixmap类中有一个静态成员
QPixmap QPixmap::grabWindow( WId window, int x = 0, int y = 0, int width = -1, int height = -1 )

1)在你的小部件上绘制渐变;

2)使用该函数将小部件的表面抓取到像素图中;WId可以从 收到QWidget::effectiveWinId ()

3)将token pixmap转换成QImage(有一个可用的构造函数);

4)返回的颜色表int QImage::pixelIndex( int x, int y )中 (x, y) 处的像素索引。QImage在您的情况下,您必须根据小部件的高度(pWidget->height() / 100 * 28.5)计算百分比值。

5)QRgb QImage::color( int i )返回颜色表中索引 i 处的颜色。

所以返回的 Color 就是您正在寻找的颜色。