How do I make JavaFX MediaView stretch media to fill parent container?

前端 未结 4 1029
故里飘歌
故里飘歌 2020-12-17 20:38

I\'m trying to make my video\'s dimensions stretch automatically and fill the MediaView and maintain the original aspect ratio of the video. Basically, I want my MediaPlayer

相关标签:
4条回答
  • 2020-12-17 21:16

    A more declarative way in a ".fxml" file would be:

    ...
    <Pane fx:id="mediaViewPane">
      <children>
         <MediaView fx:id="videoView" fitHeight="${mediaViewPane.height}" fitWidth="${mediaViewPane.width}" layoutX="1.0" />
      </children>
    </Pane>
    ...
    

    You can use the "${...}" syntax for any attribute in your ".fxml" for Expression Binding. If you want to call a UI element you have to provide a "fx:id". For example in this case it's fx:id="mediaViewPane".

    So you don't have to care about the UI stuff in your code. For me it's a little bit cleaner.

    0 讨论(0)
  • 2020-12-17 21:16

    I also struggled with this but I did this

    mediaView.fitWidthProperty().bind(stage.widthProperty());
    mediaView.fitHeightproperty().bind(stage.heightProperty());
    

    and I worked for me. The mediaView played at the same size as the stage / window. Hope it helps.

    0 讨论(0)
  • 2020-12-17 21:32

    Here's an example of stretching to the containing Scene and the scene is set by the Dimension "size":

    final MediaPlayer videoPlayer = new MediaPlayer(
        new Media(new File(videoPath).toURI().toString()));
    MediaView mv = new MediaView(videoPlayer);
    DoubleProperty mvw = mv.fitWidthProperty();
    DoubleProperty mvh = mv.fitHeightProperty();
    mvw.bind(Bindings.selectDouble(mv.sceneProperty(), "width"));
    mvh.bind(Bindings.selectDouble(mv.sceneProperty(), "height"));
    mv.setPreserveRatio(true);
    
    setScene(new Scene(new Group(mv), size.getWidth(), size.getHeight()));
    
    0 讨论(0)
  • 2020-12-17 21:34

    Just realized no-one answered this so I'll answer it.

    Just set the media player fitWidthProperty to that of the MediaView so:

    player.fitWidthProperty().bind(mediaView.widthProperty());
    

    and the same for the height (if you wanted) and also preserveRatio and stuff.

    0 讨论(0)
提交回复
热议问题