Java颜色(按年龄)



我正在编写一个显示一些图形的小应用程序,刚才我正试图根据对象的年龄(通过System.currentTimeMillis()保存)更改颜色,使最旧的对象显示为蓝色,最新的对象显示红色左右。有人知道算法级别吗?

假设您希望最旧的对象是蓝色,而最近的

// 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值扩展到最大TTL值(例如,60 seconds60000 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.

Color Color=age>5280?Color.RED:年龄>1000?Color.BLACK:年龄>30?Color.YouGetTheIdea

您可以根据每个对象的年龄(以毫秒、小时为单位)制定一个度量值,也可以根据以上内容制定自定义度量值,即任何东西<1小时是1等

这给了你衡量标准。NOw,你可以迭代对象以找到当前限制9min和max),或者你甚至可以在计算度量时这样做:每次发生小于min的事情时,存储新的min等。

现在你现在传播。最后一件事是上色。比方说,我们的对象范围从10毫秒到1000毫秒。你可以将其分为3个区域:例如,10-100、100-500、500-1000,并在此基础上应用颜色。

最新更新