動(dòng)畫的實(shí)現(xiàn)上來說,是設(shè)置定時(shí)器進(jìn)行刷新.
對(duì)于Swing程序來說java.swing.Timer類保證了線程在swing調(diào)用上的安全性。通過時(shí)間參數(shù)的設(shè)置時(shí)間動(dòng)態(tài)定時(shí)刷新,
對(duì)于動(dòng)態(tài)往復(fù)描繪來說,比如類似于動(dòng)態(tài)的顏色變化,動(dòng)態(tài)的進(jìn)行透明變化之類的周期性刷新來說,一般需要幾個(gè)條件
1.動(dòng)畫的周期性
2.動(dòng)畫的當(dāng)前狀態(tài)在起始狀態(tài)和目標(biāo)狀態(tài)之間
實(shí)現(xiàn)上需要這么幾個(gè)參數(shù)
- 起始時(shí)間 animation startTime
- 當(dāng)前時(shí)間 currentime
- 動(dòng)畫周期 animation duration
- 往返因數(shù) fraction
往返因數(shù)fraction
比如動(dòng)態(tài)調(diào)整透明度、動(dòng)態(tài)修改顏色在動(dòng)畫的過程中可以設(shè)定起始與目標(biāo)值,通過fraction在0-1范圍內(nèi)進(jìn)行運(yùn)算進(jìn)行調(diào)整。
以算法來描述則為
起始值設(shè)為 init
目標(biāo)值為 dest
實(shí)際值為 actual
actual=init*(1-fraction)+dest*fraction;
比較明顯的例子為,將顏色從初始顏色動(dòng)態(tài)變化到目標(biāo)顏色
Color startColor = Color.red; // where we start
Color endColor = Color.BLACK; // where we end
Color currentColor = startColor;
....
描繪currentColor的一個(gè)圓
在Timer的actionPerform里調(diào)整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);
通過定時(shí)器的時(shí)間參數(shù)動(dòng)態(tài)調(diào)整往返因數(shù)
通過時(shí)間參數(shù)進(jìn)行計(jì)算
如下代碼所示,在Timer的actionPerform里實(shí)現(xiàn)
long currentTime = System.nanoTime() / 1000000;
long totalTime = currentTime - animationStartTime;
//調(diào)整周期的起始時(shí)間
if (totalTime > animationDuration) {
animationStartTime = currentTime;
}
float fraction = (float)totalTime / animationDuration;
fraction = Math.min(1.0f, fraction);
注意當(dāng)前只是計(jì)算出了fraction,如何使因子在1-0和0-1之間往復(fù)變化呢
以下代碼實(shí)現(xiàn)了該算法
// 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();//重新繪制
posted on 2008-02-14 12:00
如果有一天de 閱讀(1320)
評(píng)論(1) 編輯 收藏 所屬分類:
richclient