原理是调整surfaceView大小。分为两种,一种是mediaplayer(ijkmediaplayer,exoplayer)+surfaceView,在onVideoSizeChanged()方法中调整surfaceView大小即可。
1.//一定要在setOnVideoSizeChangedListener方法中调用
mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
if (mediaPlayer.getVideoWidth() != surfaceView.getWidth() ||
mediaPlayer.getVideoHeight() != surfaceView.getHeight()){
autoFitVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
}
}
});
public void autoFitVideoSize(float surfaceWidth, float surfaceHeight) {
int videoWidth = mediaPlayer.getVideoWidth();
int videoHeight = mediaPlayer.getVideoHeight();
//根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
float max;
if (getResources().getConfiguration().orientation==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
//竖屏模式下按视频宽度计算放大倍数值
max = Math.max((float) videoWidth / (float) surfaceWidth,(float) videoHeight / (float) surfaceHeight);
} else {
//横屏模式下按视频高度计算放大倍数值
max = Math.max(((float) videoWidth/(float) surfaceHeight),(float) videoHeight/(float) surfaceWidth);
}
//视频宽高分别/最大倍数值 计算出放大后的视频尺寸
videoWidth = (int) Math.ceil((float) videoWidth / max);
videoHeight = (int) Math.ceil((float) videoHeight / max);
//无法直接设置视频尺寸,将计算出的视频尺寸设置到 surfaceView 让视频自动填充。
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
params.width = videoWidth;
params.height = videoHeight;
//setScale是为了能让画面尽可能铺满全屏,但这样牺牲了部分画面部分
surfaceView.setScaleX((float) 1.3);
surfaceView.setScaleY((float) 1.3);
surfaceView.setLayoutParams(params);
}
2.使用自定义的surfaceView,在onMeasure()方法中设置大小。
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = 1; int height = 1; if (mVideoWidth > 0 && mVideoHeight > 0) { width = getDefaultSize(mVideoWidth, widthMeasureSpec); height = getDefaultSize(mVideoHeight, heightMeasureSpec); if (mVideoWidth * height > width * mVideoHeight) { height = width * mVideoHeight / mVideoWidth; } else if (mVideoWidth * height < width * mVideoHeight) { width = height * mVideoWidth / mVideoHeight; } } Log.v(TAG,"onMeasure[" + width + ", " + height + "]"); setMeasuredDimension(width, height); }
public static int getDefaultSize(int size, int measureSpec) { int result = size; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: result = size; break; case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = specSize; break; } return result; }
也可以使用第一种方法,但是如果你的控制栏使用addView的话这样调整会导致控制栏跟随变化,如果使用的popwindow的话就没有影响。