2017-09-14 53 views
0

我正在製作一個滑動動畫來將場景切換到另一個場景,但是當我調用此方法時,它將有切換場景的延遲。我發現原因是類Scene的方法snapshot()。 有沒有人有解決方案?Javafx Scene.snapshot方法性能低下

代碼:

public void switchScene(Scene target) { 
    Scene current = getPrimaryStage().getScene(); 
    WritableImage beforeImage; 
    WritableImage afterImage; 

    int width = ((int) ((Region) current.getRoot()).getWidth()); 
    int height = ((int) ((Region) current.getRoot()).getHeight()); 

    beforeImage = new WritableImage(width, height); 
    ImageView leftImage = new ImageView(current.snapshot(beforeImage)); 

    afterImage = new WritableImage(width, height); 
    ImageView rightImage = new ImageView(target.snapshot(afterImage)); 

    leftImage.setTranslateX(0); 
    rightImage.setTranslateX(width); 

    StackPane animation = new StackPane(leftImage, rightImage); 
    animation.setPrefSize(target.getWidth(), target.getHeight()); 

    primaryStage.setScene(new Scene(animation)); 

    Timeline timeline = new Timeline(); 
    KeyValue kv = new KeyValue(rightImage.translateXProperty(), 0, Interpolator.EASE_BOTH); 
    KeyFrame kf = new KeyFrame(Duration.seconds(0.75), kv); 
    timeline.getKeyFrames().add(kf); 
    timeline.setOnFinished(t -> { 
     // remove pane and restore scene 1 
     primaryStage.setScene(target); 
    }); 
    timeline.play(); 
} 
+0

不知道你在那裏試圖做什麼。但是,爲什麼不對異步調用[snapshot](http://docs.oracle.com/javafx/2/api/javafx/scene/Scene.html#snapshot(javafx.util.Callback,%) 20javafx.scene.image.WritableImage))方法? – ItachiUchiha

回答

0

拍攝快照,以這種方式本質上是一個緩慢的操作,有沒有可以做,以加快它留在Java的土地,而很大。正如評論中所建議的那樣,如果您確實想要創建快照,那麼更好的方法是使用異步方法,它不會在UI線程運行時阻塞它(所以當它們仍然會延遲時,您的應用程序將仍然保持響應)。

但是,如果我已經正確地理解了您的示例,則完全不需要使用屏幕截圖 - 您爲什麼要使用圖像而不是僅爲節點本身設置動畫效果?請記住,所有JavaFX元素都是場景圖的節點,因此可以用相同的方式進行動畫。因此,而不是:

StackPane animation = new StackPane(leftImage, rightImage); 

你應該只能夠做到:

StackPane animation = new StackPane(source, target); 

...然後用這個動畫窗格的情況下直接通過截屏的緩慢的過程去。