1. VideoView使用小结
1.
VideoView按原始视频比例播放
int screenH; // 手机屏幕高度
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// 获取视频资源的宽度
mVideoWidth = mp.getVideoWidth();
// 获取视频资源的高度
mVideoHeight = mp.getVideoHeight();
scale = (float) mVideoWidth / (float) mVideoHeight;
refreshPortraitScreen(showVideoHeight == 0 ? screenH : showVideoHeight);
}
});
}
});
// 重新刷新 竖屏显示的大小 树屏显示以宽度为准
public void refreshPortraitScreen(int height) {
if (height == 0) {
height = showVideoHeight;
}
if (mVideoHeight > 0 && mVideoWidth > 0) {
// 拉伸比例
mVideoWidth = (int) (height * scale);// 设置surfaceview画布大小
// mVideoHeight = (int) (mVideoWidth / scale);
mVideoView.getHolder().setFixedSize(mVideoWidth, height);
// 重绘VideoView大小,这个方法是在重写VideoView时对外抛出方法
mVideoView.setMeasure(mVideoWidth, height);
mVideoView.requestLayout();
}
}
public class MyVideoView extends VideoView {
private int width;
private int height;
public DiyVideoView(Context context) {
super(context);
}
public DiyVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setMeasure(int width, int height) {
this.width = width;
this.height = height;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 默认高度,为了自动获取到focus
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width;
// 这个之前是默认的拉伸图像
if (this.width > 0 && this.height > 0) {
width = this.width;
height = this.height;
}
setMeasuredDimension(width, height);
}
}
上面3小段即可实现视频适配播放