2016-10-02 36 views
1

我想將按鈕的顏色更改爲反轉顏色,並將其作爲轉換返回。JavaFX Transition:反轉按鈕顏色

我能夠使用ColorAdjust的時間軸來做到這一點與亮度,但我沒有找到一個效果類來過渡按鈕的顏色與時間軸。

希望有人能幫助我嗎? 謝謝!

回答

1

可以通過使用Blend效應與BlendMode.DIFFERENCEtopInput來實現反轉效果,其中黑色無反轉,白色完全反轉顏色。例如:

@Override 
public void start(Stage primaryStage) { 
    Blend blendEffect = new Blend(BlendMode.DIFFERENCE); 
    ColorInput input = new ColorInput(); 
    blendEffect.setTopInput(input); 
    Button btn = new Button("Inversion Animation"); 
    input.widthProperty().bind(btn.widthProperty()); 
    input.heightProperty().bind(btn.heightProperty()); 
    btn.setEffect(blendEffect); 
    btn.setStyle("-fx-body-color: orange;"); 

    DoubleProperty brightness = new SimpleDoubleProperty(0); 
    input.paintProperty().bind(Bindings.createObjectBinding(() -> Color.BLACK.interpolate(Color.WHITE, brightness.get()), brightness)); 

    Timeline timeline = new Timeline(
      new KeyFrame(Duration.ZERO, new KeyValue(brightness, 0d)), 
      new KeyFrame(Duration.seconds(1), new KeyValue(brightness, 1d)) 
    ); 
    timeline.setOnFinished(evt -> timeline.setRate(-timeline.getRate())); 

    btn.setOnAction((ActionEvent event) -> { 
     timeline.play(); 
    }); 

    StackPane root = new StackPane(); 
    root.getChildren().add(btn); 

    Scene scene = new Scene(root, 500, 500); 

    primaryStage.setScene(scene); 
    primaryStage.show(); 
}