对于SwingE序来说java.swing.TimercM证了U程在swing调用上的安全性。通过旉参数的设|时间动态定时刷斎ͼ
对于动态往复描l来_比如cM于动态的颜色变化Q动态的q行透明变化之类的周期性刷新来_一般需要几个条?br />
1.动画的周期?br />
2.动画的当前状态在起始状态和目标状态之?br />
实现上需要这么几个参?br />
- 起始旉 animation startTime
- 当前旉 currentime
- 动画周期 animation duration
- 往q因?fraction
往q因数fraction
比如动态调整透明度、动态修攚w色在动画的过E中可以讑֮起始与目标|通过fraction?-1范围内进行运进行调整?br />
以算法来描述则ؓ
起始D?init
目标gؓ dest
实际gؓ actual
actual=init*(1-fraction)+dest*fraction;
比较明显的例子ؓQ将颜色从初始颜色动态变化到目标颜色
Color startColor = Color.red; // where we start
Color endColor = Color.BLACK; // where we end
Color currentColor = startColor;
....
描绘currentColor的一个圆
在Timer的actionPerform里调整currentColor
// interpolate between start and end colors with current fraction
int red = (int)(fraction * endColor.getRed() +
(1 - fraction) * startColor.getRed());
int green = (int)(fraction * endColor.getGreen() +
(1 - fraction) * startColor.getGreen());
int blue = (int)(fraction * endColor.getBlue() +
(1 - fraction) * startColor.getBlue());
// set our new color appropriately
currentColor = new Color(red, green, blue);
通过定时器的旉参数动态调整往q因?/h2>
通过旉参数q行计算
如下代码所C,在Timer的actionPerform里实?br />
long currentTime = System.nanoTime() / 1000000;
long totalTime = currentTime - animationStartTime;
//调整周期的v始时?br />
if (totalTime > animationDuration) {
animationStartTime = currentTime;
}
float fraction = (float)totalTime / animationDuration;
fraction = Math.min(1.0f, fraction);
注意当前只是计算ZfractionQ如何因子?-0?-1之间往复变化呢
以下代码实现了该法
// This calculation will cause alpha to go from 1 to 0 and back to 1
// as the fraction goes from 0 to 1
alpha = Math.abs(1 - (2 * fraction));
//repaint();//重新l制

]]>