了解JavaFX中的插值方法

3

我正在尝试在JavaFX中创建动画。

然而,我对一个方法的理解有困难。

有人能解释一下底部的interpolate方法具体是做什么的吗?

更具体地说,它如何使用模数?

import javafx.animation.Interpolator;
import javafx.animation.Transition;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.ImageView;
import javafx.util.Duration;

public class SpriteAnimation extends Transition {

    private  ImageView imageView;

    private  int count;            
    private  int columns;         
    private  int offsetX;         
    private  int offsetY;         
    private  int width;            
    private  int height;          
    private int lastIndex;

    public SpriteAnimation(
            ImageView imageView, 
            Duration duration, 
            int count,   int columns,
            int offsetX, int offsetY,
            int width,   int height) {

        this.imageView = imageView;       
        this.count     = count;       
        this.columns   = columns;
        this.offsetX   = offsetX;       
        this.offsetY   = offsetY;
        this.width     = width;
        this.height    = height;

        setCycleDuration(duration);  
        setInterpolator(Interpolator.LINEAR); 
    }

    protected void interpolate(double k) {
        // 
        int index = Math.min((int) Math.floor(k * count), count - 1);
        if (index != lastIndex) {

            int x = (index % columns) * width  + offsetX;
            int y = (index / columns) * height + offsetY;
            imageView.setViewport(new Rectangle2D(x, y, width, height));

            lastIndex = index;
        }
    }
}
1个回答

2

当转换运行时,不同的值将传递给插值器。在动画开始时,0.0将被传递给k,在动画结束时,1.0将被传递。

int index = Math.min((int) Math.floor(k * count), count - 1);

计算范围在0到count-1之间的索引。顺便说一下,我更喜欢(int)(k * count)而不是(int)Math.floor(k * count),因为将浮点值强制转换为int会截断小数部分。
当索引发生变化时,ImageView应该显示相应部分的图像。在这里,您需要从左到右逐行遍历精灵。
index % columns

余数是指将index除以columns的余数。这意味着每次将index增加1时,结果将增加1,直到达到columns;在这种情况下,它将重新从0开始。

由于这个属性,它可以用来确定要显示的图像的水平位置。您只需乘以精灵的宽度即可获得左侧的x坐标。

index / columns

余数为零的index除以columns得到的结果相同,即 index / columns(index - index % columns) / columns 的结果相同。每添加columnsindex值就会增加1个结果;当index % column重新从0开始时,也会增加1个结果。因此,它可以用于确定精灵的y坐标;只需将其乘以一个精灵的高度。

columns = 3的示例:

index   |   index % 3  |   index / 3
--------------------------------------
  0     |     0        |     0
  1     |     1        |     0
  2     |     2        |     0
  3     |     0        |     1
  4     |     1        |     1
  5     |     2        |     1
  6     |     0        |     2
             ...
 31     |     1        |     10

这样的话,您就可以按照以下顺序迭代精灵

-------------------
|  1  |  2  |  3  |
-------------------
|  4  |  5  |  6  |
-------------------
        ...
-------------------
| 31  | 32  |     |
-------------------

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接