ZXing.Net.Maui条码扫描器仅横屏可扫描,竖屏无法识别求助
竖屏模式下ZXing.Net.Maui无法扫描条码的问题排查与解决
我正在将现有条码扫描应用升级至.NET Maui,使用ZXing.Net.Maui控件开发。目前遇到问题:竖屏模式下无法扫描条码,但切换到横屏模式后即可正常识别。以下是我的界面布局代码和后台代码,请问遗漏了哪些配置或设置?
界面布局代码
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:zxing="clr-namespace:ZXing.Net.Maui.Controls;assembly=ZXing.Net.MAUI.Controls" x:Class="Scanner.Scan" x:DataType="Line" Title="Scan"> <ScrollView> <VerticalStackLayout Padding="30,0" Spacing="25"> <Image Source="banner2.jpg" HeightRequest="75" Aspect="AspectFit"/> <Line Stroke="Black" X2="{Binding Width, Source={RelativeSource Self}}" HorizontalOptions="Fill" StrokeThickness="2" /> <zxing:CameraBarcodeReaderView x:Name="barcodeReader" WidthRequest="350" HeightRequest="450" IsDetecting="True" IsTorchOn="False" BarcodesDetected="OnBarcodesDetected" /> <Label Text="Ready to scan." VerticalOptions="Center" HorizontalOptions="Center" /> </VerticalStackLayout> </ScrollView> </ContentPage>
后台代码
public partial class Scan : ContentPage { protected override void OnAppearing() { base.OnAppearing(); } public Scan() { InitializeComponent(); } protected void OnBarcodesDetected(object? sender, BarcodeDetectionEventArgs e) { foreach (var barcode in e.Results) { // Process the scanned barcode data //Console.WriteLine($"Barcode Format: {barcode.Format}, Value: {barcode.Value}"); } } }
问题解决步骤
移除ScrollView容器
把CameraBarcodeReaderView放在ScrollView中会导致竖屏时预览区域的触摸和识别逻辑异常,直接用VerticalStackLayout作为根布局:<ContentPage ...> <VerticalStackLayout Padding="30,0" Spacing="25"> <!-- 原有控件 --> <zxing:CameraBarcodeReaderView ... /> <!-- 原有控件 --> </VerticalStackLayout> </ContentPage>取消固定宽高,适配父容器
固定的WidthRequest和HeightRequest会让竖屏时相机预览被裁剪或拉伸,改为填充父容器并设置合理比例:<zxing:CameraBarcodeReaderView x:Name="barcodeReader" HorizontalOptions="Fill" VerticalOptions="Fill" AspectRatio="4:3" IsDetecting="True" IsTorchOn="False" BarcodesDetected="OnBarcodesDetected" />配置扫描选项适配竖屏
在OnAppearing中设置自动旋转和扫描区域,确保竖屏时识别逻辑正确:protected override void OnAppearing() { base.OnAppearing(); barcodeReader.CameraLocation = CameraLocation.Back; barcodeReader.Options = new BarcodeReaderOptions { AutoRotate = true, TryHarder = true, // 按屏幕尺寸设置扫描区域 ScanRegion = new Rect(0, 0, DeviceDisplay.Current.MainDisplayInfo.Width, DeviceDisplay.Current.MainDisplayInfo.Height) }; }确认权限配置
- Android:在AndroidManifest.xml中添加相机权限
<uses-permission android:name="android.permission.CAMERA" /> - iOS:在Info.plist中添加相机权限说明
<key>NSCameraUsageDescription</key> <string>需要使用相机扫描条码</string>
- Android:在AndroidManifest.xml中添加相机权限
内容的提问来源于stack exchange,提问作者Prescott Chartier
相关产品推荐
相关产品推荐

