Предполагая, что вы хотите, чтобы ваш самый старый объект был синим, а ваш самый новый объект - красным, и вы знаете все объекты "возраст" (назовем его timestamp
)
// mesure the difference in age of the newest and oldest objects
double agediff = newest.timestamp - oldest.timestamp;
// for any given object :
// 1. color ratio from 0.0=old to 1.0=new
double ratio = (someObject.timestamp - oldest.timestamp) / ageDiff;
// 2. get red and blue values
int red = 255 - (255 * ratio);
int blue = 255 * ratio;
// 3. construct Color
Color objectColor = new Color(red, 0, blue);
Если вы хотите масштабировать количество оттенков, которые хотите отобразить, просто округлите соотношение в соответствии с шагом.Например:
// the maximum number of shades between blue and red
int step = 4; // the value cannot be 1 (otherwise use a Color constant!)
double stepScale = 256 / (step - 1);
double halfStepScale = stepScale / 2;
ratio = Math.ceil((int) ((ratio * 256 + halfStepScale) / stepScale) * stepScale) / 256d;
Или, если вместо этого вы хотите масштабировать от новейшего до максимального значения TTL (например, 60 seconds
или 60000 millis
), просто замените oldest.timestamp
на этоЗначение и измените ваш алгоритм, чтобы включить проверку переполнения:
// our "oldest" timestamp is now pre-defined:
long oldestTs = newest.timestamp - ttlTimestamp; // ttlTimestamp = 60000;
// mesure the difference in age of the newest and the TTL (ex: 60000)
double agediff = newest.timestamp - oldestTs;
// for any given object :
// 1. color ratio from 0.0=old to 1.0=new
double ratio = (someObject.timestamp - oldestTs) / ageDiff;
if (ratio < 0.0) ratio = 0.0; // prevent overflow
// etc.
** Редактировать **
Если вы хотите другой градиент, чем синий / красный, вы можете иметь:
// green=new, yellow=old
new Color(1f - (float) ratio, 1f, 0f);
// yellow=new, green=old
new Color((float) ratio, 1f, 0f);
// green=new, red=old
new Color(1f - (float) ratio, (float) ratio, 0f);
// etc.