代码之家  ›  专栏  ›  技术社区  ›  Narek

从渐变中获取中间颜色

  •  4
  • Narek  · 技术社区  · 15 年前

    假设我有一个线性梯度,如图所示:

    QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, 100));
    linearGrad.setColorAt(1, Qt::red);
    linearGrad.setColorAt(0.5, Qt::yellow);
    linearGrad.setColorAt(0, Qt::green);
    

    如何在这个渐变中得到点QPointF(0,28.5)的颜色?

    事实上,我想有这种颜色分布能够选择中间色。我不在乎它是通过使用QLinearGradient还是其他方法来实现的。

    4 回复  |  直到 15 年前
        1
  •  3
  •   Pie_Jesu    14 年前

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

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

    3) 将令牌pixmap转换为 QImage

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

    5) QRgb QImage::color( int i )

    所以返回的颜色就是你想要的颜色。

        2
  •  9
  •   user2232395    10 年前

    我将渐变的颜色存储在一个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);
    }
    
        3
  •  4
  •   azf    11 年前

    让controlPoints()返回 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>() ;
    }
    
        4
  •  1
  •   Mason Zhang    15 年前

    QVariantAnimation具有类似的功能,QVariantAnimation::keyValueAt可以返回所需的值。您可以进入QVariantAnimation的代码,看看keyValueAt是如何工作的。