Android TvView调整宽高比:解决直播内容底部区域显示不全问题
解决TvView播放直播时底部比分被截断的问题
当使用android.media.tv.TvView在Fragment小区域播放直播时,底部内容被截断通常是因为视频原始宽高比与TvView显示区域不匹配,导致部分内容被裁剪。可以通过以下几种方式调整:
1. 修改TvView的ScaleType
TvView继承自SurfaceView,支持通过scaleType控制视频缩放逻辑。默认的CENTER_CROP会裁剪超出显示区域的内容,可改为以下类型避免底部被裁:
修改布局文件中的TvView,添加缩放属性:
<android.media.tv.TvView android:id="@+id/tvView" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitStart" />
fitStart:保持宽高比,视频顶部对齐显示区域,完整展示内容(底部可能留空,但无裁剪)fitCenter:保持宽高比,视频居中显示,上下或左右留空fitXY:强制拉伸填充整个区域,无裁剪但会导致画面变形
2. 代码动态调整缩放比例
如果ScaleType无法满足需求,可在TvView初始化完成后,根据视频原始比例动态调整缩放:
在你的Fragment代码中添加TvView回调监听:
tvView.setCallback(new TvView.TvInputCallback() { @Override public void onVideoAvailable(String inputId) { super.onVideoAvailable(inputId); // 获取视频与视图的宽高比 float videoAspectRatio = 16f / 9f; // 多数直播为16:9,可根据实际视频源调整 float viewAspectRatio = (float) tvView.getWidth() / tvView.getHeight(); if (viewAspectRatio > videoAspectRatio) { // 视图宽度偏宽,缩小宽度方向缩放,保证高度完整显示 tvView.setScaleX(videoAspectRatio / viewAspectRatio); tvView.setScaleY(1f); tvView.setPivotY(tvView.getHeight()); // 底部对齐,避免内容上移 } else { // 视图高度偏高,缩小高度方向缩放 tvView.setScaleY(viewAspectRatio / videoAspectRatio); tvView.setScaleX(1f); } } }); // 原有的初始化代码 TvInputManager mTvInputManager = (TvInputManager) requireContext() .getSystemService(Context.TV_INPUT_SERVICE); List<TvInputInfo> inputs = mTvInputManager.getTvInputList(); List<String> ids = new ArrayList<>(); for (TvInputInfo info : inputs) { if (info.getType() == type) { String id = info.getParentId() != null ? info.getParentId() : info.getId(); if (!ids.contains(id)) { ids.add(id); } } } int idx = viewModel.deviceDetails.getSettings().getOtherDetails().getPort() - 1; String id = ids.get(idx); tvView.setVisibility(View.VISIBLE); tvView.tune(id, TvContract.buildChannelUriForPassthroughInput(id));
3. 调整TvView布局尺寸
改用ConstraintLayout控制TvView的宽高比,确保视频以标准比例完整显示:
<?xml version="1.0" encoding="utf-8"?> <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"> <android.media.tv.TvView android:id="@+id/tvView" android:layout_width="match_parent" android:layout_height="0dp" android:scaleType="fitCenter" android:layout_gravity="bottom" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintDimensionRatio="16:9" /> </androidx.constraintlayout.widget.ConstraintLayout>
此配置会让TvView以16:9的比例填充宽度,底部对齐父容器,确保底部比分内容不会被裁剪。
补充说明
- 部分TvInput可能会强制控制视频缩放模式,若上述方法无效,需检查TvInput的配置或联系输入源提供商确认是否有自定义缩放接口。
- 测试时建议覆盖不同比例的视频源,确保调整后的效果适配多种场景。
内容的提问来源于stack exchange,提问作者Drunken Daddy
相关产品推荐
相关产品推荐

