Qwt源码解读之QwtColorMap颜色类

QwtColorMap是一个抽象基类,用于将值映射到颜色。Qwt实现了其两个派生子类QwtLinearColorMap和QwtAlphaColorMap。继承关系如下:

我们首先看看QwtColorMap的代码:

class QWT_EXPORT QwtColorMap
{
public:
    /*!
        Format for color mapping
        \sa rgb(), colorIndex(), colorTable()
    */

    enum Format
    {
        //! The map is intended to map into QRgb values.
        RGB,

        /*!
          The map is intended to map into 8 bit values, that
          are indices into the color table.
         */
        Indexed
    };

    QwtColorMap( Format = QwtColorMap::RGB );
    virtual ~QwtColorMap();

    Format format() const;

    /*!
       Map a value of a given interval into a rgb value.
       \param interval Range for the values
       \param value Value
       \return rgb value, corresponding to value
    */
    virtual QRgb rgb( const QwtInterval &interval,
        double value ) const = 0;

    /*!
       Map a value of a given interval into a color index
       \param interval Range for the values
       \param value Value
       \return color index, corresponding to value
     */
    virtual unsigned char colorIndex(
        const QwtInterval &interval, double value ) const = 0;

    QColor color( const QwtInterval &, double value ) const;
    virtual QVector<QRgb> colorTable( const QwtInterval & ) const;

private:
    Format d_format;
};
通过重新实现两个纯虚函数,可以根据需要定制颜色映射关系类,从而实现各种各样的颜色杆。


现在再看看QwtLinearColorMap的实现代码:

/*!
  Map a value of a given interval into a rgb value

  \param interval Range for all values
  \param value Value to map into a rgb value
*/
QRgb QwtLinearColorMap::rgb(
    const QwtInterval &interval, double value ) const
{
    if ( qIsNaN(value) )
        return qRgba(0, 0, 0, 0);

    const double width = interval.width();

    double ratio = 0.0;
    if ( width > 0.0 )
        ratio = ( value - interval.minValue() ) / width;

    return d_data->colorStops.rgb( d_data->mode, ratio );
}

/*!
  Map a value of a given interval into a color index, between 0 and 255

  \param interval Range for all values
  \param value Value to map into a color index
*/
unsigned char QwtLinearColorMap::colorIndex(
    const QwtInterval &interval, double value ) const
{
    const double width = interval.width();

    if ( qIsNaN(value) || width <= 0.0 || value <= interval.minValue() )
        return 0;

    if ( value >= interval.maxValue() )
        return ( unsigned char )255;

    const double ratio = ( value - interval.minValue() ) / width;

    unsigned char index;
    if ( d_data->mode == FixedColors )
        index = ( unsigned char )( ratio * 255 ); // always floor
    else
        index = ( unsigned char )qRound( ratio * 255 );

    return index;
}

注意实现代码的细节,特别是对特殊情况的处理。



你可能感兴趣的:(qwt)