【问题标题】:javafx - Changing the image of an ImageView using timeline doesn't workjavafx - 使用时间轴更改 ImageView 的图像不起作用
【发布时间】:2017-10-04 17:10:14
【问题描述】:

我想显示一个精灵动画,使用 ImageView 作为图像的容器和 TimeLine 来切换 imageview 中的图像:

private ImageView imgView;
...
public void init(Image[] images) {
   this.imgView = new ImageView(images[0]);
   Timeline timeLine = new Timeline();
   Collection<KeyFrame> frames = timeLine.getKeyFrames();
   for (Image img : images)
       frames.add(new KeyFrame(Duration.millis(256), e -> imgView.setImage(img)));

   timeLine.setCycleCount(Timeline.INDEFINITE);
   timeLine.play();
}

ImageView 被渲染,但卡在动画的某些图像上(甚至不是第一个)。就像我只会将一张图像放入 imageview 并且永远不会更改它。 我在 ImageView 的 imageproperty 中添加了一个 ChangeListener,输出 imageview 的当前图像。它确实在根据需要进行更改,但仍然只渲染了一张图像。图像肯定不同,我仔细检查了。为什么imageproperty改变后imageview没有更新?

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    您对所有关键帧使用相同的时间点,因此对imgView.setImage(...) 的所有调用都发生在“同一时间”。只有最后一次这样的调用才会有任何可见的效果,因为前面的调用之间没有时间。

    您需要使图像视图的图像的每次更改发生在不同的时间。比如:

    public void init(Image[] images) {
        this.imgView = new ImageView(images[0]);
        Timeline timeLine = new Timeline();
        Collection<KeyFrame> frames = timeLine.getKeyFrames();
        Duration frameGap = Duration.millis(256);
        Duration frameTime = Duration.ZERO ;
        for (Image img : images) {
            frameTime = frameTime.add(frameGap);
            frames.add(new KeyFrame(frameTime, e -> imgView.setImage(img)));
        }
        timeLine.setCycleCount(Timeline.INDEFINITE);
        timeLine.play();
    }
    

    【讨论】:

    • 谢谢你,这对我有帮助!显然我误解了 Duration 参数的含义。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多