我有一个这样设置的 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 匹配父级的高度,同时保持纵横比不变,视频将被剪裁在两侧。
我设法拉伸(stretch) 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();
}
});
这很好用,并且 Controller 始终保持打开状态,但在计算放置视频的位置时没有考虑 Controller 的高度(因为它是垂直居中的)。
我的两个问题是:
- 如何使 VideoView 匹配父级的高度同时保持纵横比?
- 如何让 VideoView 考虑其 Controller 的高度?
谢谢。
最佳答案
您应该从内置视频 View 扩展。
在显示视频 View 之前调用setVideoSize
,您可以从视频中提取的缩略图中获取视频大小。
因此,当调用视频 View 的 onMeasure
时,mVideoWidth
和 mVideoHeight
均 > 0。
如果你想考虑 Controller 的高度,你可以在 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);
}
}
关于android - VideoView 匹配父高度并保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603553/