36

我有一个这样设置的 VideoView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:id="@+id/player" 
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <VideoView
        android:id="@+id/video"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true" />

    <ProgressBar
        android:id="@+id/loader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

但是VideoView匹配父容器的宽度,然后根据加载的影片的纵横比设置高度。
我想做相反的事情,我希望 VideoView 匹配父级的高度,同时保持纵横比不变,视频将被剪裁在两侧。

我设法拉伸 VideoView 以填充父级,但没有保留纵横比。

另一件事是,我将 MediaController 添加到 VideoView 中,如下所示:

MediaController controllers = new MediaController(this) {
    @Override
    public void hide() {
        if (state != State.Hidden) {
            this.show();
        }
        else {
            super.hide();
        }
    }
};
controllers.setAnchorView(videoView);
videoView.setMediaController(controllers);

videoView.setOnPreparedListener(new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        controllers.show();
    }
});

这很好用,并且控制器始终保持打开状态,但是在计算放置视频的位置时没有考虑控制器的高度(因为它是垂直居中的)。

那么我的两个问题是:

  1. 如何使 VideoView 与父级的高度匹配但保持纵横比?
  2. 如何让 VideoView 考虑其控制器的高度?

谢谢。

4

12 回答 12

31

您应该从内置视频视图扩展。

在显示视频视图之前调用setVideoSize,您可以从视频中提取的缩略图中获取视频大小。

因此,当onMeasure调用视频视图时,mVideoWidth&mVideoHeight都 > 0。

如果你想考虑控制器的高度,你可以在onMeasure方法中自己做。

希望会有所帮助。

public class MyVideoView extends VideoView {

        private int mVideoWidth;
        private int mVideoHeight;

        public MyVideoView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public MyVideoView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        public MyVideoView(Context context) {
            super(context);
        }

        public void setVideoSize(int width, int height) {
            mVideoWidth = width;
            mVideoHeight = height;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            // Log.i("@@@", "onMeasure");
            int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
            int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
            if (mVideoWidth > 0 && mVideoHeight > 0) {
                if (mVideoWidth * height > width * mVideoHeight) {
                    // Log.i("@@@", "image too tall, correcting");
                    height = width * mVideoHeight / mVideoWidth;
                } else if (mVideoWidth * height < width * mVideoHeight) {
                    // Log.i("@@@", "image too wide, correcting");
                    width = height * mVideoWidth / mVideoHeight;
                } else {
                    // Log.i("@@@", "aspect ratio is correct: " +
                    // width+"/"+height+"="+
                    // mVideoWidth+"/"+mVideoHeight);
                }
            }
            // Log.i("@@@", "setting size: " + width + 'x' + height);
            setMeasuredDimension(width, height);
        }
}
于 2013-09-29T06:44:20.210 回答
18

我用布局解决了这个问题。当它被固定在角落时,它似乎工作正常,但它导致视频倾斜。为了测试,我将相对布局的背景更改为 #990000 以查看红色戳穿。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relative_parent"
    android:background="#000000">
    <VideoView
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:id="@+id/videoView" />
</RelativeLayout>
于 2015-07-30T21:01:08.903 回答
13

关于问题 1,我很惊讶没有人提到可能使用 MediaPlayer 的缩放模式。 https://developer.android.com/reference/android/media/MediaPlayer.html#setVideoScalingMode(int)

它有2种模式。它们都总是填充视图区域。要让它在保持纵横比的同时填充空间,从而裁剪长边,您需要切换到第二种模式,VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING. 这解决了问题的一部分。另一部分是改变 VideoView 的测量行为,正如其他一些答案所展示的那样。这就是我这样做的方式,主要是出于懒惰并且不熟悉其他人使用的元数据 API,欢迎您使用此方法或其他方法之一来修复视图的大小。在 mMediaPlayer 存在之前调用它时,毯子捕获可确保安全,因为它可能会被多次调用,并且如果字段名称发生更改,它也会回退到旧行为。

class FixedSizeVideoView : VideoView {
    constructor(ctx: Context) : super(ctx)
    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)

    // rather than shrink down to fit, stay at the size requested by layout params. Let the scaling mode
    // of the media player shine through. If the scaling mode on the media player is set to the one
    // with cropping, you can make a player similar to AVLayerVideoGravityResizeAspectFill on iOS
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        try {
            val mpField = VideoView::class.java.getDeclaredField("mMediaPlayer")
            mpField.isAccessible = true
            val mediaPlayer: MediaPlayer = mpField.get(this) as MediaPlayer

            val width = View.getDefaultSize(mediaPlayer.videoWidth, widthMeasureSpec)
            val height = View.getDefaultSize(mediaPlayer.videoHeight, heightMeasureSpec)
            setMeasuredDimension(width, height)
        }
        catch (ex: Exception) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }
}

因此,在布局中使用此类,您只需在有机会的地方更改媒体播放器上的缩放模式。如:

        video.setOnPreparedListener { mp: MediaPlayer ->
            mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
            mp.isLooping = true
            mp.setScreenOnWhilePlaying(false)
        }
        video.start()
于 2017-10-27T19:41:30.637 回答
7
public class MyVideoView extends VideoView {
    private int mVideoWidth;
    private int mVideoHeight;

    public MyVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyVideoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyVideoView(Context context) {
        super(context);
    }


    @Override
    public void setVideoURI(Uri uri) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(this.getContext(), uri);
        mVideoWidth = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
        mVideoHeight = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
        super.setVideoURI(uri);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Log.i("@@@", "onMeasure");
        int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
        int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
        if (mVideoWidth > 0 && mVideoHeight > 0) {
            if (mVideoWidth * height > width * mVideoHeight) {
                // Log.i("@@@", "image too tall, correcting");
                height = width * mVideoHeight / mVideoWidth;
            } else if (mVideoWidth * height < width * mVideoHeight) {
                // Log.i("@@@", "image too wide, correcting");
                width = height * mVideoWidth / mVideoHeight;
            } else {
                // Log.i("@@@", "aspect ratio is correct: " +
                // width+"/"+height+"="+
                // mVideoWidth+"/"+mVideoHeight);
            }
        }
        // Log.i("@@@", "setting size: " + width + 'x' + height);
        setMeasuredDimension(width, height);
    }
}
于 2016-11-07T22:42:02.233 回答
6

使用 ConstraintLayout 我们可以实现这一点,参考下面的 xml 代码。

当 layout_width 和 layout_height 为 0dp 时,VideoView 的大小和位置是根据其他约束动态计算的。layout_constraintDimensionRatio 属性表示app在计算VideoView的大小时,宽高比应该是3:4。此约束使视频的纵横比保持不变,并防止视图在任一方向上被拉伸得太远(取决于设备的旋转方式)。

根据要求纵向/横向更改 layout_constraintDimensionRatio 值。

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="3:4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
于 2020-08-12T20:11:58.457 回答
5

快速有效的修复:

无需创建从 VideoView 扩展的自定义视图。只需设置一个足够大的值即可android:layout_width。这会将widthSpecMode视频视图设置为View.MeasureSpec.AT_MOST,然后onMeasure()VideoView 的方法将自动调整其宽度,保持比例。

<VideoView
     android:id="@+id/video"
     android:layout_width="2000dp"
     android:layout_height="match_parent" />
于 2018-10-15T17:36:26.023 回答
2

第一次一个问题回答了我的问题而不是答案!我的问题是我在全屏视频下有一个空白区域。我正在设置layout_heightmatch_parent. 解决方案是将其设置为wrap_content并为父级提供黑色背景。那,并且VideoView在其父级中垂直居中。

我将其写为评论,但后来认为有人可能遇到与我相同的问题,所以这里也作为答案。

于 2019-03-22T10:35:33.390 回答
1

我尝试了很多解决方案,而我的视频始终是 1000*1000 格式,所以我为知道宽高比的人创建了一个简单的解决方案。首先在 RelativeLayout 中创建一个 VideoView,如下所示:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/video_holder"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:clipToPadding="false">

      <VideoView  
          android:id="@+id/videoView"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_alignParentBottom="true"
          android:layout_alignParentEnd="true"
          android:layout_alignParentStart="true"
          android:layout_alignParentTop="true" />
</RelativeLayout>

然后在加载视频之前更改高度,并以如下方式编程:

    int i = videoView.getHeight() > videoView.getWidth() ? videoView.getHeight() : videoView.getWidth();
    video_holder.setLayoutParams(new ConstraintLayout.LayoutParams(i, i));

当然,这只适用于 1:1 的纵横比,但您可以使用纵横比来更改高度或宽度。

于 2017-12-21T15:05:49.957 回答
1

Jobbert 在 Kotlin 中的回答,以防有人需要:

val max = if (videoView.height > videoView.width) videoView.height else videoView.width
videoView.layoutParams = ConstraintLayout.LayoutParams(max, max)
于 2018-07-20T10:18:01.943 回答
-1

只需将您的 VideoView 放入 RelativeLayout 并为该相对布局设置所需的大小。像下面的代码,

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="300dp">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true" />

</RelativeLayout>

它会起作用的。

于 2020-05-07T15:52:44.547 回答
-1

我一直在寻找在 VideoView 中以方面填充显示视频的方法,但是在尝试了许多解决方案之后,它们似乎都不起作用。

所以我实施了以下方法,它对我有用:

代码:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    // getting screen size
    ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int width = displayMetrics.widthPixels;
    int height = displayMetrics.heightPixels;

    double videoSizeRatio = (double) mVideoHeight / mVideoWidth;
    double screenSizeRatio = (double) height / width;

    if (mVideoWidth > 0 && mVideoHeight > 0) {
        if (videoSizeRatio > screenSizeRatio) { // screen is wider than video width
            height = (int) (videoSizeRatio * width);
        } else if (videoSizeRatio < screenSizeRatio) {
            width = (int) (height / videoSizeRatio);
        }

    }
    setMeasuredDimension(width, height);
}

布局:

 <YourCustomizedVideoView
    android:id="@+id/videoView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    />
于 2020-01-30T04:19:05.627 回答
-3

您只需将 Videoview 小部件放入 RelativeLayout(仅限 xml 文件中的更改)

这是参考答案链接

于 2020-04-29T05:36:30.740 回答