如何调整Fragment中HMS Scan Kit CustomizedView缩放比例解决视图拉伸问题?
解决非全屏Fragment中相机取景器拉伸问题
匹配相机预览与View的宽高比
取景器拉伸的核心原因是相机预览尺寸和View的宽高比不匹配。在CustomizedView中重写onMeasure方法,强制保持相机支持的预览比例:@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 替换为你的相机实际支持的预览比例(比如16:9或4:3) float targetRatio = 16f / 9f; int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); float currentViewRatio = (float) width / height; if (currentViewRatio > targetRatio) { // 视图过宽,按高度计算适配后的宽度 width = (int) (height * targetRatio); } else { // 视图过高,按宽度计算适配后的高度 height = (int) (width / targetRatio); } setMeasuredDimension(width, height); }修正Fragment布局约束
不要给CustomizedView设置match_parent后强制填满父布局,比如使用ConstraintLayout时,给View添加比例约束:<com.yourpackage.CustomizedView android:id="@+id/camera_view" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintDimensionRatio="16:9" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/>确保View按固定比例展示,而非被拉伸填充。
延迟相机初始化至View测量完成
Fragment中View的尺寸在onCreateView阶段尚未确定,此时初始化相机会导致预览尺寸计算错误。在onViewCreated中监听View布局完成事件,再初始化相机:@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); CustomizedView cameraView = view.findViewById(R.id.camera_view); cameraView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { cameraView.getViewTreeObserver().removeOnGlobalLayoutListener(this); // 传入View实际宽高初始化相机预览 cameraView.initCamera(cameraView.getWidth(), cameraView.getHeight()); } }); }排除系统窗口对View尺寸的干扰
如果Activity非全屏,给CustomizedView设置android:fitsSystemWindows="false",避免系统自动添加内边距导致View比例变形;同时确保Fragment的布局没有被状态栏、导航栏挤压导致尺寸异常。
内容的提问来源于stack exchange,提问作者ImamFF
相关产品推荐
相关产品推荐

