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;
}

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



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值