Android VideoView Proportional Scaling

前端 未结 3 1808
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 10:13

In Android\'s VideoView, is there any way to achieve the same effect as ImageView.ScaleType.CENTER_CROP?

That is, I want my VideoView to play the video such that it

3条回答
  •  半阙折子戏
    2020-12-17 10:58

    In Android's VideoView, here is a simple and easy way to achieve the same effect as ImageView.ScaleType.CENTER_CROP

    XML

    
    
    
        
    
    
    

    In Kotlin:

    videoView.setOnPreparedListener { mediaPlayer ->
        val videoRatio = mediaPlayer.videoWidth / mediaPlayer.videoHeight.toFloat()
        val screenRatio = videoView.width / videoView.height.toFloat()
        val scaleX = videoRatio / screenRatio
        if (scaleX >= 1f) {
            videoView.scaleX = scaleX
        } else {
            videoView.scaleY = 1f / scaleX
        }
    }
    

    In JAVA:

    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
          float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
          float screenRatio = videoView.getWidth() / (float) 
          videoView.getHeight();
          float scaleX = videoRatio / screenRatio;
          if (scaleX >= 1f) {
              videoView.setScaleX(scaleX);
          } else {
              videoView.setScaleY(1f / scale);
          }
       }
    });
    

    And this worked for me. Hope this will help someone.

提交回复
热议问题