You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow Lite目标检测示例横屏模式相机无法全屏问题求助

TensorFlow Lite目标检测横屏相机全屏适配方案

问题原因

官方示例默认针对竖屏场景做了适配,横屏切换后出现以下两个核心问题:

  1. 相机预览尺寸选择逻辑未适配横屏宽高比,导致选中的相机分辨率与屏幕比例不匹配,画面被裁剪或留黑边
  2. 横屏时相机显示方向与屏幕方向未同步,进一步加剧画面显示异常

解决步骤

1. 修复相机预览尺寸选择逻辑

找到CameraConnectionFragment中的chooseOptimalSize方法,修改宽高比对逻辑,适配横屏场景:

private Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight) {
    boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    // 横屏时交换目标宽高,匹配相机尺寸的宽高定义
    int targetWidth = isLandscape ? textureViewWidth : textureViewHeight;
    int targetHeight = isLandscape ? textureViewHeight : textureViewWidth;

    List<Size> bigEnough = new ArrayList<>();
    for (Size option : choices) {
        // 横屏时优先选择宽>高的尺寸,且比例接近屏幕
        if ((isLandscape && option.getWidth() >= targetWidth && option.getHeight() >= targetHeight)
                || (!isLandscape && option.getHeight() >= targetWidth && option.getWidth() >= targetHeight)) {
            bigEnough.add(option);
        }
    }

    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else {
        return choices[0];
    }
}

2. 确保预览视图铺满屏幕

检查activity_camera.xml中的预览控件(通常是TextureView)布局参数,强制设置全屏:

<TextureView
    android:id="@+id/texture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="0dp"
    android:padding="0dp" />

同时在CameraConnectionFragment的onViewCreated方法中,动态设置视图参数:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    TextureView textureView = view.findViewById(R.id.texture);
    ViewGroup.LayoutParams params = textureView.getLayoutParams();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    params.height = ViewGroup.LayoutParams.MATCH_PARENT;
    textureView.setLayoutParams(params);
}

3. 同步相机与屏幕方向

在CameraConnectionFragment的setUpCameraOutputs方法中,根据屏幕方向调整相机显示方向:

private void setUpCameraOutputs(int width, int height) {
    // ... 原有代码 ...
    int displayOrientation;
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        displayOrientation = 0; // 或根据设备相机传感器方向调整为180
    } else {
        displayOrientation = 90;
    }
    camera.setDisplayOrientation(displayOrientation);
    // ... 原有代码 ...
}

内容的提问来源于stack exchange,提问作者Abdul Rafey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:55:30