VideoView 萬能適配
阿新 • • 發佈:2019-02-10
用VideoView進行視訊播放的時候,因為視訊資源本身尺寸原因,如果VideoView不做任何處理,播放效果總不盡人意。
對VideoView進行了簡單封裝,但是已經達到了想要的播放效果。
我想要的效果是:
程式碼:
public class CustomVideoView extends VideoView {
//最終的視訊資源寬度
private int mVideoWidth=480;
//最終視訊資源高度
private int mVideoHeight=480;
//視訊資源原始寬度
private int videoRealW=1;
//視訊資源原始高度
private int videoRealH=1;
public CustomVideoView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomVideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
public void setVideoPath(String path) {
super.setVideoPath(path);
MediaMetadataRetriever retr = new MediaMetadataRetriever();
retr.setDataSource(path);
String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 視訊高度
String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 視訊寬度
try {
videoRealH=Integer.parseInt(height);
videoRealW=Integer.parseInt(width);
} catch (NumberFormatException e) {
Log.e("----->" + "VideoView", "setVideoPath:" + e.toString());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(0, widthMeasureSpec);
int height = getDefaultSize(0, heightMeasureSpec);
if(height>width){
//豎屏
if(videoRealH>videoRealW){
//如果視訊資源是豎屏
//佔滿螢幕
mVideoHeight=height;
mVideoWidth=width;
}else {
//如果視訊資源是橫屏
//寬度佔滿,高度儲存比例
mVideoWidth=width;
float r=videoRealH/(float)videoRealW;
mVideoHeight= (int) (mVideoWidth*r);
}
}else {
//橫屏
if(videoRealH>videoRealW){
//如果視訊資源是豎屏
//寬度佔滿,高度儲存比例
mVideoHeight=height;
float r=videoRealW/(float)videoRealH;
mVideoWidth= (int) (mVideoHeight*r);
}else {
//如果視訊資源是橫屏
//佔滿螢幕
mVideoHeight=height;
mVideoWidth=width;
}
}
if(videoRealH==videoRealW&&videoRealH==1){
//沒能獲取到視訊真實的寬高,自適應就可以了,什麼也不用做
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
}else {
setMeasuredDimension(mVideoWidth, mVideoHeight);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
//遮蔽觸控點選事件
return true;
}
}
改變螢幕方向,它會自動適應