gpt4 book ai didi

Java 按年龄划分颜色

转载 作者:行者123 更新时间:2023-12-01 15:29:16 25 4
gpt4 key购买 nike

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

最佳答案

假设您希望最旧对象为蓝色,最新对象为红色,并且您知道所有对象“年龄”(我们称之为时间戳)

// 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 秒60000 毫秒),只需替换 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.

关于Java 按年龄划分颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com