我在Android中使用 Mediaplayer 在线播放视频并在 videoview 上显示。视频视图放在具有固定大小的 RelativeLayout 中。
问题是视频的大小(视频的宽度和高度)不适合相对布局,因此我需要调整视频大小以适应内部相对布局,并且视频的比例正好,但它看起来并不像工作,我的代码在这里:
***用于创建视频视图的代码:
...
MyVideoView mVideoView = new MyVideoView(mContext);
mVideoView.requestFocus();
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
mVideoView.setLayoutParams(p);
return mVideoView;
}
***播放视频时获取比率的代码
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mWebview.removeView(mProgressWheel);
mediaPlayer.start();
// int w = mediaPlayer.getVideoWidth();
// int h = mediaPlayer.getVideoHeight();
int w = mVideoView.getWidth();
int h = mVideoView.getHeight();
((MyVideoView) mVideoView).setDimention(w, h);
}
***我的自定义视频观看课程的简称:
public class MyVideoView extends VideoView{
...
private ElementObject elm;
private int aW;
private int aH;
int additional = 0;
float ratio = 1f;
private void caculateRatio(int w, int h){
if(w > h) ratio = (float)w/h;
else if(h > w) ratio = (float)h/w;
}
public void setDimention(int w, int h){
this.aW = w;
this.aH = h;
setIsPlaying(true);
caculateRatio(w, h);
calculateAdditional(w, h);
}
public void calculateAdditional(int w, int h){
if(w >= elm.frame.getW() && h < elm.frame.getH()) {
additional = elm.frame.getH() - h;
measure(w + (int) (additional * ratio), elm.frame.getH());
}else if(w < elm.frame.getW() && h >= elm.frame.getH()) {
additional = elm.frame.getW() - w;
measure(elm.frame.getW(), h + (int) (additional * ratio));
}else if(w < elm.frame.getW() && h < elm.frame.getH()){
int wR = elm.frame.getW() - w;
int hR = elm.frame.getH() - h;
if(wR > hR){
additional = wR;
measure(elm.frame.getW(), h + (int) (additional * ratio));
}else {
additional = hR;
measure(w + (int) (additional * ratio), elm.frame.getH());
}
}
else
measure(w, h);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//super.setMeasuredDimension(1000,1000);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
}
我发现在视频开始播放之前多次调用覆盖函数onMeasure(int, int)
,因此我删除了onMeasure(int, int)
函数并在旁边函数中调用:setMeasuredDimension(int, int)
:{{1}而不是使用public void calculateAdditional(int w, int h){...}
,但它也不会影响任何东西。
我该怎么做才能调整视频大小,使其与精确的比例完全吻合。
同时尝试更改layoutparams,将视频视图创建为 FILL_PARENT 或 MATCH_PARENT ,但保持错误。
答案 0 :(得分:0)
改为使用FILL_PARENT
:
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);