CameraX安卓横竖屏预览适配问题:横屏预览异常求助
CameraX横竖屏全屏预览异常修复方案
核心问题分析
横屏预览异常的本质是硬编码旋转角度、固定宽高比导致的——CameraX预览需要动态匹配当前屏幕的旋转状态和预览容器的比例,手动固定参数会让横竖屏切换时预览画面与实际显示区域不匹配。
具体修复步骤
1. 动态绑定屏幕旋转角度
不要硬写Surface.ROTATION_90,而是根据当前Activity的窗口旋转动态设置:
// 获取当前屏幕旋转角度 int currentRotation = getWindowManager().getDefaultDisplay().getRotation(); Preview preview = new Preview.Builder() .setTargetRotation(currentRotation) .setTargetAspectRatio(AspectRatio.RATIO_MATCH_PARENT) // 匹配容器比例 .build();
2. 监听配置变化,实时更新预览
在Activity中重写onConfigurationChanged,横竖屏切换时及时更新预览的旋转参数:
@Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); // 获取新的旋转角度 int newRotation = getWindowManager().getDefaultDisplay().getRotation(); // 更新预览旋转 preview.setTargetRotation(newRotation); // 重新绑定预览用例到生命周期 if (cameraProvider != null) { cameraProvider.unbindAll(); cameraProvider.bindToLifecycle(this, cameraSelector, preview); } }
3. 配置预览容器与Activity属性
- 布局中使用
PreviewView并设置全屏:
<androidx.camera.view.PreviewView android:id="@+id/previewView" android:layout_width="match_parent" android:layout_height="match_parent" />
- 在
AndroidManifest.xml中给Activity添加配置,避免横竖屏重启:
<activity android:name=".YourCameraActivity" android:configChanges="orientation|screenSize|screenLayout" />
4. 可选:自定义预览缩放模式
如果需要更精准的全屏适配,可以设置PreviewView的缩放模式:
previewView.setScaleType(PreviewView.ScaleType.FILL_START); // 或者根据需求选择FILL_CENTER/FILL_END等
为什么之前的方法无效?
- 硬编码
ROTATION_90会导致横屏时旋转角度与实际屏幕方向不匹配,画面出现拉伸/偏移; - 固定
AspectRatio.RATIO_16_9会强制预览比例,当容器是竖屏比例时横屏切换后必然出现黑边或拉伸; - 单独用矩阵处理没有联动CameraX的预览用例配置,无法从根源解决旋转和比例适配问题。
内容的提问来源于stack exchange,提问作者nicover
相关产品推荐
相关产品推荐

