2011-01-06 151 views
41

因此,我擴展了VideoView的onMeasure以放大視頻以適應全屏視圖。在VideoView中放置視頻

這裏是如何:

public void setVideoAspect(int w,int h){ 
    wVideo=w; 
    hVideo=h; 
    onMeasure(w, h); 
} 
@Override 
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) 
{ 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    if(wVideo!=0 && hVideo!=0) 
    setMeasuredDimension(wVideo,hVideo); 
} 

我打電話與屏幕的顯示的指標(寬度,高)setVideoAspect()。問題是這種方法會將視頻延伸到屏幕內部。我希望能夠保持寬高比。 (I具有4:3視頻和3:2的屏幕尺寸。)我使用瞭如下因素代碼,得到保留比測量到視圖:

int height = (int) (metrics.widthPixels*3/(float)4); 
         int width= metrics.widthPixels; 
         mVideoView.setVideoAspect(width,height); 

所以這不會工作,但存在這樣的問題:它使我使用屏幕寬度的4:3視頻並正確縮放高度,但不會使視頻居中。 (它只是裁剪視頻的底部,而不是頂部和底部)。我有一個包含VideoView的相對佈局,並將VideoView的引力設置爲居中。

+0

能你爲此提供了完整的代碼...我堅持不住 – 2018-01-22 11:59:30

回答

106

嘗試使用FrameLayout代替。我不知道爲什麼,但如果我在我的代碼中使用線性或相對,它不會居中,但框架會。這裏是一個適合我的視頻畫面,保存率和定心它的XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:background="@drawable/bg"> 
<!-- Video player --> 
<VideoView android:id="@+id/surface_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_gravity="center"> 
</VideoView> 
</FrameLayout> 
+0

我的代碼是否適用於此? – DArkO 2011-02-01 04:14:41

+1

如果你對Android自動調整視頻大小(如果在橫向上,很可能會垂直填充屏幕,然後將水平大小保持比例),我認爲你不需要任何代碼。它應該與該代碼一起工作,但如果您仍然需要它,無論出於何種原因 – Cameron 2011-02-01 13:40:19

+2

我不知道爲什麼,但是當在VideoView中搜索對齊視頻時,Google不會顯示它。在我得到這個相關的答案之前,我不得不開始寫這個問題。謝謝! :) – jlindenbaum 2011-05-17 21:18:16

7

爲中心的視頻在RelativeLayout的我加了兩個layout_gravity="center"廣告layout_centerInParent="true"。它適用於我的Android 4.3手機。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <VideoView android:id="@+id/surface_view" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_gravity="center" 
     android:layout_centerInParent="true" /> 
</RelativeLayout> 
7

卡梅隆的以編程的方式應答(萬一有人像我一樣需要它)這個代碼是內部的活動的onCreate在我的代碼(「這」下面是指活動)

FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
      LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 

    FrameLayout fl = new FrameLayout(this); 

    fl.setLayoutParams(lp); 

    VideoView vv = new VideoView(this); 

    FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(lp); 

    lp2.gravity = Gravity.CENTER; 

    vv.setLayoutParams(lp2); 

    fl.addView(vv); 

    setContentView(fl);