笔头。。
实践启示
posts - 14,comments - 3,trackbacks - 0
动画的实现上来说,是设置定时器进行刷新.
对于Swing程序来说java.swing.Timer类保证了线程在swing调用上的安全性。通过时间参数的设置时间动态定时刷新,
对于动态往复描绘来说,比如类似于动态的颜色变化,动态的进行透明变化之类的周期性刷新来说,一般需要几个条件
1.动画的周期性
2.动画的当前状态在起始状态和目标状态之间
实现上需要这么几个参数
  • 起始时间 animation startTime
  • 当前时间 currentime
  • 动画周期 animation duration
  • 往返因数 fraction

    往返因数fraction

    比如动态调整透明度、动态修改颜色在动画的过程中可以设定起始与目标值,通过fraction在0-1范围内进行运算进行调整。
以算法来描述则为
  起始值设为 init
  目标值为 dest
  实际值为 actual
    actual=init*(1-fraction)+dest*fraction;
  比较明显的例子为,将颜色从初始颜色动态变化到目标颜色
 
  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);

通过定时器的时间参数动态调整往返因数

    通过时间参数进行计算
    如下代码所示,在Timer的actionPerform里实现
            long currentTime = System.nanoTime() / 1000000;
            
long totalTime = currentTime - animationStartTime;
            //调整周期的起始时间
            if (totalTime > animationDuration) {
                animationStartTime 
= currentTime;
            }
            
float fraction = (float)totalTime / animationDuration;
            fraction 
= Math.min(1.0f, fraction);
     注意当前只是计算出了fraction,如何使因子在1-0和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();//重新绘制


posted on 2008-02-14 12:00 如果有一天de 阅读(1297) 评论(1)  编辑  收藏 所属分类: richclient

FeedBack:
# re: swing Timer 与 animation 之 技巧一让往返因数 fraction从1到0再从0到1
2008-02-17 12:28 | 519virus
非常不错呀……   回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: