在Android中,避免Letterbox(黑邊)內容變形的關鍵是確保視頻播放器的尺寸與視頻內容的尺寸相匹配。以下是一些建議來實現這一目標:
使用FitVideoView
或TextureView
:這些視圖可以自動調整大小以適應視頻內容,從而避免Letterbox變形。
設置視頻的縮放模式:在加載視頻時,設置視頻的縮放模式為fitXY
或centerCrop
。這將確保視頻填充整個播放區域,同時保持其寬高比。
VideoView videoView = findViewById(R.id.videoView);
videoView.setVideoURI(Uri.parse("your_video_url"));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_FIT_XY); // 或者使用 centerCrop
videoView.start();
}
});
AspectRatioFrameLayout
:將視頻播放器放置在AspectRatioFrameLayout
中,并設置其寬高比。這將確保視頻播放器始終保持所需的寬高比,同時填充整個屏幕。<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.AspectRatioFrameLayout
android:id="@+id/video_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5"
app:layout_constraintHorizontal_bias="0.5">
<VideoView
android:id="@+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.AspectRatioFrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
private VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = findViewById(R.id.videoView);
videoView.setVideoURI(Uri.parse("your_video_url"));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
updateVideoSize();
videoView.start();
}
});
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
updateVideoSize();
}
private void updateVideoSize() {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int screenHeight = getResources().getDisplayMetrics().heightPixels;
float videoAspectRatio = (float) videoView.getDuration() / videoView.getVideoWidth();
int videoHeight = (int) (screenWidth / videoAspectRatio);
ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
layoutParams.width = screenWidth;
layoutParams.height = videoHeight;
videoView.setLayoutParams(layoutParams);
}
}
遵循這些建議,您應該能夠避免在Android應用程序中使用Letterbox時出現內容變形的問題。