QGIS API Documentation  2.3.0-Master
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
qgsvectorcolorrampv2.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorcolorrampv2.cpp
3  ---------------------
4  begin : November 2009
5  copyright : (C) 2009 by Martin Dobias
6  email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgsvectorcolorrampv2.h"
17 #include "qgscolorbrewerpalette.h"
18 #include "qgscptcityarchive.h"
19 
20 #include "qgssymbollayerv2utils.h"
21 #include "qgsapplication.h"
22 #include "qgslogger.h"
23 
24 #include <stdlib.h> // for random()
25 #include <QTime>
26 
28 
29 static QColor _interpolate( QColor c1, QColor c2, double value )
30 {
31  int r = ( int )( c1.red() + value * ( c2.red() - c1.red() ) );
32  int g = ( int )( c1.green() + value * ( c2.green() - c1.green() ) );
33  int b = ( int )( c1.blue() + value * ( c2.blue() - c1.blue() ) );
34  int a = ( int )( c1.alpha() + value * ( c2.alpha() - c1.alpha() ) );
35 
36  return QColor::fromRgb( r, g, b, a );
37 }
38 
40 
42  bool discrete, QgsGradientStopsList stops )
43  : mColor1( color1 ), mColor2( color2 ), mDiscrete( discrete ), mStops( stops )
44 {
45 }
46 
48 {
49  // color1 and color2
52  if ( props.contains( "color1" ) )
53  color1 = QgsSymbolLayerV2Utils::decodeColor( props["color1"] );
54  if ( props.contains( "color2" ) )
55  color2 = QgsSymbolLayerV2Utils::decodeColor( props["color2"] );
56 
57  //stops
59  if ( props.contains( "stops" ) )
60  {
61  foreach ( QString stop, props["stops"].split( ':' ) )
62  {
63  int i = stop.indexOf( ';' );
64  if ( i == -1 )
65  continue;
66 
67  QColor c = QgsSymbolLayerV2Utils::decodeColor( stop.mid( i + 1 ) );
68  stops.append( QgsGradientStop( stop.left( i ).toDouble(), c ) );
69  }
70  }
71 
72  // discrete vs. continuous
73  bool discrete = false;
74  if ( props.contains( "discrete" ) )
75  {
76  if ( props["discrete"] == "1" )
77  discrete = true;
78  }
79 
80  // search for information keys starting with "info_"
82  for ( QgsStringMap::const_iterator it = props.constBegin();
83  it != props.constEnd(); ++it )
84  {
85  if ( it.key().startsWith( "info_" ) )
86  info[ it.key().mid( 5 )] = it.value();
87  }
88 
89  QgsVectorGradientColorRampV2* r = new QgsVectorGradientColorRampV2( color1, color2, discrete, stops );
90  r->setInfo( info );
91  return r;
92 }
93 
95 {
96  if ( index <= 0 )
97  {
98  return 0;
99  }
100  else if ( index >= mStops.size() + 1 )
101  {
102  return 1;
103  }
104  else
105  {
106  return mStops[index-1].offset;
107  }
108 }
109 
110 QColor QgsVectorGradientColorRampV2::color( double value ) const
111 {
112  if ( mStops.isEmpty() )
113  {
114  if ( mDiscrete )
115  return mColor1;
116  return _interpolate( mColor1, mColor2, value );
117  }
118  else
119  {
120  double lower = 0, upper = 0;
121  QColor c1 = mColor1, c2;
122  for ( QgsGradientStopsList::const_iterator it = mStops.begin(); it != mStops.end(); ++it )
123  {
124  if ( it->offset > value )
125  {
126  if ( mDiscrete )
127  return c1;
128 
129  upper = it->offset;
130  c2 = it->color;
131 
132  return upper == lower ? c1 : _interpolate( c1, c2, ( value - lower ) / ( upper - lower ) );
133  }
134  lower = it->offset;
135  c1 = it->color;
136  }
137 
138  if ( mDiscrete )
139  return c1;
140 
141  upper = 1;
142  c2 = mColor2;
143  return upper == lower ? c1 : _interpolate( c1, c2, ( value - lower ) / ( upper - lower ) );
144  }
145 }
146 
148 {
150  mDiscrete, mStops );
151  r->setInfo( mInfo );
152  return r;
153 }
154 
156 {
157  QgsStringMap map;
158  map["color1"] = QgsSymbolLayerV2Utils::encodeColor( mColor1 );
159  map["color2"] = QgsSymbolLayerV2Utils::encodeColor( mColor2 );
160  if ( !mStops.isEmpty() )
161  {
162  QStringList lst;
163  for ( QgsGradientStopsList::const_iterator it = mStops.begin(); it != mStops.end(); ++it )
164  {
165  lst.append( QString( "%1;%2" ).arg( it->offset ).arg( QgsSymbolLayerV2Utils::encodeColor( it->color ) ) );
166  }
167  map["stops"] = lst.join( ":" );
168  }
169 
170  map["discrete"] = mDiscrete ? "1" : "0";
171 
172  for ( QgsStringMap::const_iterator it = mInfo.constBegin();
173  it != mInfo.constEnd(); ++it )
174  {
175  map["info_" + it.key()] = it.value();
176  }
177 
178  return map;
179 }
181 {
182  if ( discrete == mDiscrete )
183  return;
184 
185  // if going to/from Discrete, re-arrange stops
186  // this will only work when stops are equally-spaced
187  QgsGradientStopsList newStops;
188  if ( discrete )
189  {
190  // re-arrange stops offset
191  int numStops = mStops.count() + 2;
192  int i = 1;
193  for ( QgsGradientStopsList::const_iterator it = mStops.begin();
194  it != mStops.end(); ++it )
195  {
196  newStops.append( QgsGradientStop(( double ) i / numStops, it->color ) );
197  if ( i == numStops - 1 )
198  break;
199  i++;
200  }
201  // replicate last color
202  newStops.append( QgsGradientStop(( double ) i / numStops, mColor2 ) );
203  }
204  else
205  {
206  // re-arrange stops offset, remove duplicate last color
207  int numStops = mStops.count() + 2;
208  int i = 1;
209  for ( QgsGradientStopsList::const_iterator it = mStops.begin();
210  it != mStops.end(); ++it )
211  {
212  newStops.append( QgsGradientStop(( double ) i / ( numStops - 2 ), it->color ) );
213  if ( i == numStops - 3 )
214  break;
215  i++;
216  }
217  }
218  mStops = newStops;
219  mDiscrete = discrete;
220 }
221 
222 void QgsVectorGradientColorRampV2::addStopsToGradient( QGradient* gradient, double alpha )
223 {
224  //copy color ramp stops to a QGradient
225  QColor color1 = mColor1;
226  QColor color2 = mColor2;
227  if ( alpha < 1 )
228  {
229  color1.setAlpha( color1.alpha() * alpha );
230  color2.setAlpha( color2.alpha() * alpha );
231  }
232  gradient->setColorAt( 0, color1 );
233  gradient->setColorAt( 1, color2 );
234 
235  for ( QgsGradientStopsList::const_iterator it = mStops.begin();
236  it != mStops.end(); ++it )
237  {
238  QColor rampColor = it->color;
239  if ( alpha < 1 )
240  {
241  rampColor.setAlpha( rampColor.alpha() * alpha );
242  }
243  gradient->setColorAt( it->offset , rampColor );
244  }
245 }
246 
247 
249 
250 
252  int satMin, int satMax, int valMin, int valMax )
253  : mCount( count ), mHueMin( hueMin ), mHueMax( hueMax ),
254  mSatMin( satMin ), mSatMax( satMax ), mValMin( valMin ), mValMax( valMax )
255 {
256  updateColors();
257 }
258 
260 {
265 
266  if ( props.contains( "count" ) ) count = props["count"].toInt();
267  if ( props.contains( "hueMin" ) ) hueMin = props["hueMin"].toInt();
268  if ( props.contains( "hueMax" ) ) hueMax = props["hueMax"].toInt();
269  if ( props.contains( "satMin" ) ) satMin = props["satMin"].toInt();
270  if ( props.contains( "satMax" ) ) satMax = props["satMax"].toInt();
271  if ( props.contains( "valMin" ) ) valMin = props["valMin"].toInt();
272  if ( props.contains( "valMax" ) ) valMax = props["valMax"].toInt();
273 
274  return new QgsVectorRandomColorRampV2( count, hueMin, hueMax, satMin, satMax, valMin, valMax );
275 }
276 
278 {
279  if ( mColors.size() < 1 ) return 0;
280  return index / mColors.size() - 1;
281 }
282 
283 QColor QgsVectorRandomColorRampV2::color( double value ) const
284 {
285  int colorCnt = mColors.count();
286  int colorIdx = ( int )( value * colorCnt );
287 
288  if ( colorIdx >= 0 && colorIdx < colorCnt )
289  return mColors.at( colorIdx );
290 
291  return QColor();
292 }
293 
295 {
297 }
298 
300 {
301  QgsStringMap map;
302  map["count"] = QString::number( mCount );
303  map["hueMin"] = QString::number( mHueMin );
304  map["hueMax"] = QString::number( mHueMax );
305  map["satMin"] = QString::number( mSatMin );
306  map["satMax"] = QString::number( mSatMax );
307  map["valMin"] = QString::number( mValMin );
308  map["valMax"] = QString::number( mValMax );
309  return map;
310 }
311 
313 {
314  int h, s, v;
315 
316  mColors.clear();
317  //start hue at random angle
318  double currentHueAngle = 360.0 * ( double )rand() / RAND_MAX;
319 
320  for ( int i = 0; i < mCount; i++ )
321  {
322  //increment hue by golden ratio (approx 137.507 degrees)
323  //as this minimises hue nearness as count increases
324  //see http://basecase.org/env/on-rainbows for more details
325  currentHueAngle += 137.50776;
326  //scale hue to between mHueMax and mHueMin
327  h = ( fmod( currentHueAngle, 360.0 ) / 360.0 ) * ( mHueMax - mHueMin ) + mHueMin;
328  s = ( rand() % ( mSatMax - mSatMin + 1 ) ) + mSatMin;
329  v = ( rand() % ( mValMax - mValMin + 1 ) ) + mValMin;
330  mColors.append( QColor::fromHsv( h, s, v ) );
331  }
332 }
333 
335 
337 {
338  srand( QTime::currentTime().msec() );
339 }
340 
342 {
343 
344 }
345 
347 {
348  return INT_MAX;
349 }
350 
351 double QgsRandomColorsV2::value( int index ) const
352 {
353  Q_UNUSED( index );
354  return 0.0;
355 }
356 
357 QColor QgsRandomColorsV2::color( double value ) const
358 {
359  Q_UNUSED( value );
360  int minVal = 130;
361  int maxVal = 255;
362  int h = 1 + ( int )( 360.0 * rand() / ( RAND_MAX + 1.0 ) );
364  int v = ( rand() % ( maxVal - minVal + 1 ) ) + minVal;
365  return QColor::fromHsv( h, s, v );
366 }
367 
368 QString QgsRandomColorsV2::type() const
369 {
370  return "randomcolors";
371 }
372 
374 {
375  return new QgsRandomColorsV2();
376 }
377 
379 {
380  return QgsStringMap();
381 }
382 
384 
386  : mSchemeName( schemeName ), mColors( colors )
387 {
388  loadPalette();
389 }
390 
392 {
395 
396  if ( props.contains( "schemeName" ) )
397  schemeName = props["schemeName"];
398  if ( props.contains( "colors" ) )
399  colors = props["colors"].toInt();
400 
401  return new QgsVectorColorBrewerColorRampV2( schemeName, colors );
402 }
403 
405 {
407 }
408 
410 {
412 }
413 
415 {
416  return QgsColorBrewerPalette::listSchemeVariants( schemeName );
417 }
418 
420 {
421  if ( mPalette.size() < 1 ) return 0;
422  return index / mPalette.size() - 1;
423 }
424 
425 QColor QgsVectorColorBrewerColorRampV2::color( double value ) const
426 {
427  if ( mPalette.isEmpty() || value < 0 || value > 1 )
428  return QColor( 255, 0, 0 ); // red color as a warning :)
429 
430  int paletteEntry = ( int )( value * mPalette.count() );
431  if ( paletteEntry >= mPalette.count() )
432  paletteEntry = mPalette.count() - 1;
433  return mPalette.at( paletteEntry );
434 }
435 
437 {
439 }
440 
442 {
443  QgsStringMap map;
444  map["schemeName"] = mSchemeName;
445  map["colors"] = QString::number( mColors );
446  return map;
447 }
448 
449 
451 
452 
453 QgsCptCityColorRampV2::QgsCptCityColorRampV2( QString schemeName, QString variantName,
454  bool doLoadFile )
456  mSchemeName( schemeName ), mVariantName( variantName ),
457  mVariantList( QStringList() ), mFileLoaded( false ), mMultiStops( false )
458 {
459  // TODO replace this with hard-coded data in the default case
460  // don't load file if variant is missing
461  if ( doLoadFile && ( variantName != QString() || mVariantList.isEmpty() ) )
462  loadFile();
463 }
464 
465 QgsCptCityColorRampV2::QgsCptCityColorRampV2( QString schemeName, QStringList variantList,
466  QString variantName, bool doLoadFile )
468  mSchemeName( schemeName ), mVariantName( variantName ),
469  mVariantList( variantList ), mFileLoaded( false ), mMultiStops( false )
470 {
472 
473  // TODO replace this with hard-coded data in the default case
474  // don't load file if variant is missing
475  if ( doLoadFile && ( variantName != QString() || mVariantList.isEmpty() ) )
476  loadFile();
477 }
478 
480 {
483 
484  if ( props.contains( "schemeName" ) )
485  schemeName = props["schemeName"];
486  if ( props.contains( "variantName" ) )
487  variantName = props["variantName"];
488 
489  return new QgsCptCityColorRampV2( schemeName, variantName );
490 }
491 
493 {
494  QgsCptCityColorRampV2* ramp = new QgsCptCityColorRampV2( "", "", false );
495  ramp->copy( this );
496  return ramp;
497 }
498 
500 {
501  if ( ! other )
502  return;
503  mColor1 = other->color1();
504  mColor2 = other->color2();
505  mDiscrete = other->isDiscrete();
506  mStops = other->stops();
507  mSchemeName = other->mSchemeName;
508  mVariantName = other->mVariantName;
509  mVariantList = other->mVariantList;
510  mFileLoaded = other->mFileLoaded;
511 }
512 
514 {
517  // add author and copyright information
518  // TODO also add COPYING.xml file/link?
520  info["cpt-city-gradient"] = "<cpt-city>/" + mSchemeName + mVariantName + ".svg";
521  QString copyingFilename = copyingFileName();
522  copyingFilename.remove( QgsCptCityArchive::defaultBaseDir() );
523  info["cpt-city-license"] = "<cpt-city>" + copyingFilename;
524  ramp->setInfo( info );
525  return ramp;
526 }
527 
528 
530 {
531  QgsStringMap map;
532  map["schemeName"] = mSchemeName;
533  map["variantName"] = mVariantName;
534  return map;
535 }
536 
537 
539 {
540  if ( mSchemeName == "" )
541  return QString();
542  else
543  {
544  return QgsCptCityArchive::defaultBaseDir() + QDir::separator() + mSchemeName + mVariantName + ".svg";
545  }
546 }
547 
549 {
550  return QgsCptCityArchive::findFileName( "COPYING.xml", QFileInfo( fileName() ).dir().path(),
552 }
553 
555 {
556  return QgsCptCityArchive::findFileName( "DESC.xml", QFileInfo( fileName() ).dir().path(),
558 }
559 
561 {
563 }
564 
566 {
567  if ( mFileLoaded )
568  {
569  QgsDebugMsg( "File already loaded for " + mSchemeName + mVariantName );
570  return true;
571  }
572 
573  // get filename
574  QString filename = fileName();
575  if ( filename.isNull() )
576  {
577  QgsDebugMsg( "Couldn't get fileName() for " + mSchemeName + mVariantName );
578  return false;
579  }
580 
581  QgsDebugMsg( QString( "filename= %1 loaded=%2" ).arg( filename ).arg( mFileLoaded ) );
582 
583  // get color ramp from svg file
584  QMap< double, QPair<QColor, QColor> > colorMap =
586 
587  // add colors to palette
588  mFileLoaded = false;
589  mStops.clear();
590  QMap<double, QPair<QColor, QColor> >::const_iterator it, prev;
591  // first detect if file is gradient is continuous or dicrete
592  // discrete: stop contains 2 colors and first color is identical to previous second
593  // multi: stop contains 2 colors and no relation with previous stop
594  mDiscrete = false;
595  mMultiStops = false;
596  it = prev = colorMap.constBegin();
597  while ( it != colorMap.constEnd() )
598  {
599  // look for stops that contain multiple values
600  if ( it != colorMap.constBegin() && ( it.value().first != it.value().second ) )
601  {
602  if ( it.value().first == prev.value().second )
603  {
604  mDiscrete = true;
605  break;
606  }
607  else
608  {
609  mMultiStops = true;
610  break;
611  }
612  }
613  prev = it;
614  ++it;
615  }
616 
617  // fill all stops
618  it = prev = colorMap.constBegin();
619  while ( it != colorMap.constEnd() )
620  {
621  if ( mDiscrete )
622  {
623  // mPalette << qMakePair( it.key(), it.value().second );
624  mStops.append( QgsGradientStop( it.key(), it.value().second ) );
625  }
626  else
627  {
628  // mPalette << qMakePair( it.key(), it.value().first );
629  mStops.append( QgsGradientStop( it.key(), it.value().first ) );
630  if (( mMultiStops ) &&
631  ( it.key() != 0.0 && it.key() != 1.0 ) )
632  {
633  mStops.append( QgsGradientStop( it.key(), it.value().second ) );
634  }
635  }
636  prev = it;
637  ++it;
638  }
639 
640  // remove first and last items (mColor1 and mColor2)
641  if ( ! mStops.isEmpty() && mStops.first().offset == 0.0 )
642  mColor1 = mStops.takeFirst().color;
643  if ( ! mStops.isEmpty() && mStops.last().offset == 1.0 )
644  mColor2 = mStops.takeLast().color;
645 
646  mFileLoaded = true;
647  return true;
648 }
649 
static QgsVectorColorRampV2 * create(const QgsStringMap &properties=QgsStringMap())
static QgsVectorColorRampV2 * create(const QgsStringMap &properties=QgsStringMap())
static unsigned index
#define DEFAULT_CPTCITY_VARIANTNAME
double value(int index) const
QgsVectorGradientColorRampV2(QColor color1=DEFAULT_GRADIENT_COLOR1, QColor color2=DEFAULT_GRADIENT_COLOR2, bool discrete=false, QgsGradientStopsList stops=QgsGradientStopsList())
void copy(const QgsCptCityColorRampV2 *other)
static QList< int > listSchemeVariants(QString schemeName)
QgsVectorColorRampV2 * clone() const
#define QgsDebugMsg(str)
Definition: qgslogger.h:36
static QString defaultBaseDir()
#define DEFAULT_COLORBREWER_SCHEMENAME
#define DEFAULT_RANDOM_HUE_MIN
static QColor _interpolate(QColor c1, QColor c2, double value)
void setInfo(const QgsStringMap &info)
static QList< int > listSchemeVariants(QString schemeName)
static QColor decodeColor(QString str)
#define DEFAULT_CPTCITY_SCHEMENAME
QMap< QString, QString > QgsStringMap
Definition: qgis.h:416
#define DEFAULT_RANDOM_SAT_MAX
static QString encodeColor(QColor color)
virtual QgsStringMap properties() const
virtual QgsStringMap properties() const
QString variantName() const
virtual QColor color(double value) const
QStringList variantList() const
#define DEFAULT_GRADIENT_COLOR2
static QList< QColor > listSchemeColors(QString schemeName, int colors)
QgsVectorRandomColorRampV2(int count=DEFAULT_RANDOM_COUNT, int hueMin=DEFAULT_RANDOM_HUE_MIN, int hueMax=DEFAULT_RANDOM_HUE_MAX, int satMin=DEFAULT_RANDOM_SAT_MIN, int satMax=DEFAULT_RANDOM_SAT_MAX, int valMin=DEFAULT_RANDOM_VAL_MIN, int valMax=DEFAULT_RANDOM_VAL_MAX)
QColor color(double value) const
#define DEFAULT_GRADIENT_COLOR1
#define DEFAULT_RANDOM_VAL_MAX
QgsStringMap copyingInfo() const
virtual double value(int index) const
static QMap< QString, QString > copyingInfo(const QString &fileName)
virtual QgsStringMap properties() const
virtual double value(int index) const
virtual QgsStringMap properties() const
#define DEFAULT_RANDOM_SAT_MIN
static QgsVectorColorRampV2 * create(const QgsStringMap &properties=QgsStringMap())
virtual QColor color(double value) const
virtual QgsVectorColorRampV2 * clone() const
QgsVectorGradientColorRampV2 * cloneGradientRamp() const
int ANALYSIS_EXPORT lower(int n, int i)
lower function
QList< QgsGradientStop > QgsGradientStopsList
virtual double value(int index) const
#define DEFAULT_COLORBREWER_COLORS
static QStringList listSchemes()
const QgsGradientStopsList & stops() const
virtual QgsVectorColorRampV2 * clone() const
static QgsVectorColorRampV2 * create(const QgsStringMap &properties=QgsStringMap())
#define DEFAULT_RANDOM_HUE_MAX
virtual QgsVectorColorRampV2 * clone() const
QgsCptCityColorRampV2(QString schemeName=DEFAULT_CPTCITY_SCHEMENAME, QString variantName=DEFAULT_CPTCITY_VARIANTNAME, bool doLoadFile=true)
QgsStringMap properties() const
static QMap< double, QPair< QColor, QColor > > gradientColorMap(const QString &fileName)
note not available in python bindings
QgsVectorColorBrewerColorRampV2(QString schemeName=DEFAULT_COLORBREWER_SCHEMENAME, int colors=DEFAULT_COLORBREWER_COLORS)
virtual QColor color(double value) const
#define DEFAULT_RANDOM_VAL_MIN
void addStopsToGradient(QGradient *gradient, double alpha=1)
copy color ramp stops to a QGradient
QString copyingFileName() const
#define DEFAULT_RANDOM_COUNT
static QString findFileName(const QString &target, const QString &startDir, const QString &baseDir)
virtual QgsVectorColorRampV2 * clone() const