
如何构建.NET MAUI条形码扫描器 SDK 应用程序
.NET MAUI实现了以单一代码库同时面向 Android、iOS 和 Windows 的承诺。 真正的挑战在于如何集成条形码扫描等原生硬件功能。 手动桥接相机 API 意味着需要进行平台特定的配置、条件编译指令,以及花费数小时进行调试。 还有一条更快捷的路。
本教程将向您展示如何使用IronBarcode在.NET MAUI中构建一个可工作的跨平台条形码扫描器。 您将设置项目、配置平台权限、扫描图像文件中的条形码、读取 PDF 文档中的条形码,并使用扫描选项处理多种条形码——所有这些都可以通过您可以在任何受支持的目标上运行的代码完成。
开始免费试用,并按照以下步骤操作。
如何在 .NET MAUI 中设置条码扫描器 SDK?
设置 .NET MAUI BarCode 扫描仪 SDK 需要创建一个新项目、安装 NuGet 软件包并配置平台权限。 在 Visual Studio 中,整个配置过程只需几分钟。
创建 .NET MAUI 项目
打开 Visual Studio,创建一个新的 .NET MAUI App 项目。 将项目命名为类似"条形码扫描器"这样的描述性名称,并选择.NET 8 或更高版本作为目标框架。 Visual Studio 会生成默认项目结构,其中包含 Android 和 iOS 平台特定的文件夹。
如果您面向的是.NET 10,则相同的项目模板也适用。 将net10.0-windows10.0.19041.0,以满足要求。 有关目标框架名称和最低操作系统版本要求的完整列表,请参阅.NET MAUI支持的平台文档。
安装 IronBarcode
使用程序包管理器控制台安装IronBarcode NuGet程序包:
此命令下载并安装条形码扫描器 SDK 以及.NET MAUI应用程序所需的所有依赖项。
配置平台权限
即使扫描的是图像文件而不是实时摄像头画面,为.NET MAUI条形码扫描器应用程序配置以下权限也是很好的做法。
对于Android,将以下内容添加到Platforms/Android/AndroidManifest.xml中:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
对于iOS,将这些条目添加到Platforms/iOS/Info.plist中:
<key>NSPhotoLibraryUsageDescription</key>
<string>Access needed to select barcode images for scanning.</string>
<key>NSCameraUsageDescription</key>
<string>Camera permission for barcode scanning.</string>
初始化 SDK.
在应用程序生命周期的早期阶段设置许可证密钥,以确保在发出任何扫描调用之前IronBarcode已完全激活。 将激活放置在MauiProgram.cs中:
using IronBarCode;
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
// Activate IronBarcode before the app starts
License.LicenseKey = "YOUR_LICENSE_KEY_HERE";
return builder.Build();Imports IronBarCode
Dim builder = MauiApp.CreateBuilder()
builder _
.UseMauiApp(Of App)() _
.ConfigureFonts(Sub(fonts)
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular")
End Sub)
' Activate IronBarcode before the app starts
License.LicenseKey = "YOUR_LICENSE_KEY_HERE"
Return builder.Build()IronBarcode提供免费试用许可证,供开发和测试使用。 在启动时设置一次密钥;在相同进程中,所有对BarcodeWriter的后续调用都会使用已激活的许可证。
如何从图像文件中读取条形码?
MAUI条码扫描器的核心功能是读取选定图像中的条码。 BarcodeResult对象的集合,每个对象对应检测到的一个条形码。
设计用户界面
在MainPage.xaml中创建一个简洁的界面,允许用户选择图像文件并查看扫描到的条形码数据:
<?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"
x:Class="BarcodeScanner.MainPage">
<VerticalStackLayout Padding="20" Spacing="15">
<Label Text=".NET MAUI Barcode Scanner" FontSize="24" HorizontalOptions="Center"/>
<Button Text="Select Image to Scan" Clicked="OnSelectImageClicked"/>
<Image x:Name="SelectedImageView" HeightRequest="200"/>
<Label x:Name="ResultLabel" FontSize="16"/>
</VerticalStackLayout>
</ContentPage>
实施条形码扫描
将扫描逻辑添加到MainPage.xaml.cs中。 此代码通过MAUI FilePicker API处理图像选择,并将选定的文件路径传递给IronBarcode:
using IronBarCode;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void OnSelectImageClicked(object sender, EventArgs e)
{
var result = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle = "Select a barcode image"
});
if (result != null)
{
// Display the selected image
SelectedImageView.Source = ImageSource.FromFile(result.FullPath);
// Read barcodes from the image file
var barcodes = BarcodeReader.Read(result.FullPath);
ResultLabel.Text = barcodes.Any()
? $"Found: {barcodes.First().Value}"
: "No barcodes detected in selected image.";
}
}
}Imports IronBarCode
Public Partial Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
End Sub
Private Async Sub OnSelectImageClicked(sender As Object, e As EventArgs)
Dim result = Await FilePicker.PickAsync(New PickOptions With {
.FileTypes = FilePickerFileType.Images,
.PickerTitle = "Select a barcode image"
})
If result IsNot Nothing Then
' Display the selected image
SelectedImageView.Source = ImageSource.FromFile(result.FullPath)
' Read barcodes from the image file
Dim barcodes = BarcodeReader.Read(result.FullPath)
ResultLabel.Text = If(barcodes.Any(), $"Found: {barcodes.First().Value}", "No barcodes detected in selected image.")
End If
End Sub
End Class输出

BarcodeReader.Read()方法分析所选图像并返回所有检测到的条形码。 IronBarcode可自动识别多种条形码符号,包括 QR 码、Code 128、Code 39、EAN-13 和许多其他支持的格式。 结果集合提供了类似于PageNumber的属性,以及每个检测到的代码的边界框坐标。
如何扫描 PDF 文档中的 BarCode?
IronBarcode与其他许多同类产品的一个显著区别在于,它可以直接从 PDF 文件中读取条形码。 对于处理文档工作流程的.NET MAUI应用程序来说,这一点至关重要——发货清单、采购订单、医疗记录和类似用例都依赖于嵌入 PDF 的条形码。
PageNumber属性,该属性标识每个条形码来自哪个PDF页面:
using IronBarCode;
private async void OnSelectPdfClicked(object sender, EventArgs e)
{
var result = await FilePicker.PickAsync(new PickOptions
{
PickerTitle = "Select a PDF with barcodes"
});
if (result != null)
{
// Read barcodes from every page of the PDF
var barcodes = BarcodeReader.ReadPdf(result.FullPath);
var output = string.Join("\n", barcodes.Select(b =>
$"Page {b.PageNumber}: [{b.BarcodeType}] {b.Value}"));
await DisplayAlert("Scan Results", output.Length > 0 ? output : "No barcodes found.", "OK");
}
}Imports IronBarCode
Private Async Sub OnSelectPdfClicked(sender As Object, e As EventArgs)
Dim result = Await FilePicker.PickAsync(New PickOptions With {
.PickerTitle = "Select a PDF with barcodes"
})
If result IsNot Nothing Then
' Read barcodes from every page of the PDF
Dim barcodes = BarcodeReader.ReadPdf(result.FullPath)
Dim output = String.Join(vbLf, barcodes.Select(Function(b) $"Page {b.PageNumber}: [{b.BarcodeType}] {b.Value}"))
Await DisplayAlert("Scan Results", If(output.Length > 0, output, "No barcodes found."), "OK")
End If
End Sub输出

ReadPdf()方法扫描PDF的所有页面,并返回条形码数据和页码,使其处理包含多个条形码的文档变得简单明了。 如果PDF跨越几十页,考虑传递一个PageNumbers设置为特定范围,以限制扫描到相关页面并减少处理时间。
如何处理多个 BarCode 和 QR 码?
生产应用经常需要从单个图像中检测多个条形码,或者按条形码类型筛选结果。 BarcodeReaderOptions类公开了控制检测行为的配置属性。 将true告诉读取器在第一个匹配之后继续扫描,而不是过早停止:
using IronBarCode;
// Configure the reader for multi-barcode detection with type filtering
var options = new BarcodeReaderOptions
{
ExpectMultipleBarcodes = true,
ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
Speed = ReadingSpeed.Balanced
};
var barcodes = BarcodeReader.Read(imagePath, options);
foreach (var barcode in barcodes)
{
Console.WriteLine($"Type: {barcode.BarcodeType}, Value: {barcode.Value}");
}Imports IronBarCode
' Configure the reader for multi-barcode detection with type filtering
Dim options As New BarcodeReaderOptions With {
.ExpectMultipleBarcodes = True,
.ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
.Speed = ReadingSpeed.Balanced
}
Dim barcodes = BarcodeReader.Read(imagePath, options)
For Each barcode In barcodes
Console.WriteLine($"Type: {barcode.BarcodeType}, Value: {barcode.Value}")
NextSpeed属性控制扫描时间和准确性之间的权衡。 ReadingSpeed.ExtraSlow为具有挑战性的输入(低对比度、倾斜角度或部分被遮挡的代码)应用更积极的图像校正。 ReadingSpeed.Balanced是大多数应用程序的正确起点。
BarcodeEncoding枚举支持按位组合,因此您可以将扫描限制在与用例相关的符号上,而不会因为不必要的检查而影响性能。
如何从内存流中读取条形码?
文件路径在大多数情况下都能很好地工作,但某些.NET MAUI工作流会通过内存传递图像数据——从相机预览捕获的帧、从 REST API 下载的字节或进程内生成的图像数据。 IronBarcode在System.IO.Stream输入:
using IronBarCode;
using System.IO;
// Read a barcode from a MemoryStream (e.g., an in-memory image buffer)
private BarcodeResult[] ReadFromStream(Stream imageStream)
{
return BarcodeReader.Read(imageStream);
}
// Example: download an image and scan without writing to disk
private async Task<string> ScanDownloadedBarcode(string imageUrl)
{
using var httpClient = new HttpClient();
using var stream = await httpClient.GetStreamAsync(imageUrl);
using var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
memoryStream.Position = 0;
var barcodes = BarcodeReader.Read(memoryStream);
return barcodes.Any() ? barcodes.First().Value : string.Empty;
}Imports IronBarCode
Imports System.IO
Imports System.Net.Http
Imports System.Threading.Tasks
' Read a barcode from a MemoryStream (e.g., an in-memory image buffer)
Private Function ReadFromStream(imageStream As Stream) As BarcodeResult()
Return BarcodeReader.Read(imageStream)
End Function
' Example: download an image and scan without writing to disk
Private Async Function ScanDownloadedBarcode(imageUrl As String) As Task(Of String)
Using httpClient As New HttpClient()
Using stream As Stream = Await httpClient.GetStreamAsync(imageUrl)
Using memoryStream As New MemoryStream()
Await stream.CopyToAsync(memoryStream)
memoryStream.Position = 0
Dim barcodes = BarcodeReader.Read(memoryStream)
Return If(barcodes.Any(), barcodes.First().Value, String.Empty)
End Using
End Using
End Using
End Function流重载接受任何FileStream和网络流。 该库在内部处理格式检测,因此您无需在调用Read()之前指定图像类型。
如何在MAUI应用程序中生成条形码?
IronBarcode既能生成条形码,也能读取条形码。 Stream实例的形式生成条形码,您可以在MAUI视图中内联显示这些实例。 这对于需要打印或共享条形码以及具备扫描功能的库存管理应用程序非常有用:
using IronBarCode;
// Generate a QR code and display it in a MAUI Image control
private async void OnGenerateQrClicked(object sender, EventArgs e)
{
// Create a QR code barcode
var qrCode = QRCodeWriter.CreateQrCode(
value: "https://ironsoftware.com/csharp/barcode/",
qrCodeSize: 500,
errorCorrection: QRCodeWriter.QrErrorCorrectionLevel.Medium
);
// Save to a temporary file and display
var tempPath = Path.Combine(FileSystem.CacheDirectory, "generated-qr.png");
qrCode.SaveAsPng(tempPath);
GeneratedImageView.Source = ImageSource.FromFile(tempPath);
}Imports IronBarCode
' Generate a QR code and display it in a MAUI Image control
Private Async Sub OnGenerateQrClicked(sender As Object, e As EventArgs)
' Create a QR code barcode
Dim qrCode = QRCodeWriter.CreateQrCode(
value:="https://ironsoftware.com/csharp/barcode/",
qrCodeSize:=500,
errorCorrection:=QRCodeWriter.QrErrorCorrectionLevel.Medium
)
' Save to a temporary file and display
Dim tempPath = Path.Combine(FileSystem.CacheDirectory, "generated-qr.png")
qrCode.SaveAsPng(tempPath)
GeneratedImageView.Source = ImageSource.FromFile(tempPath)
End SubQRCodeWriter类支持所有四个QR纠错级别(低、中、四分位、高)、自定义大小和样式选项,包括前景/背景颜色控制。 对于非QR符号学,使用具有适当BarcodeWriter.CreateBarcode()。 条形码生成 API 参考文档记录了所有支持的输出格式。
该条码扫描器库的主要功能有哪些?
IronBarcode为.NET MAUI条码扫描项目提供了几个优势,使其区别于 ZXing .NET.MAUI 等开源替代方案:
| 能力 | 细节 |
|---|---|
| 跨平台支持 | 通过单个NuGet包即可支持 Android、iOS 和 Windows 平台 |
| 多个输入源 | 从文件路径、内存流和 PDF 文档进行扫描 |
| 格式覆盖 | 可解码 30 多种一维和二维条码,包括 QR 码、Data Matrix 码和 PDF417 码。 |
| 条形码生成 | 生成 PNG、位图或流输出格式的二维码和一维条形码 |
| 图像校正 | 自动处理旋转、倾斜和低对比度的输入图像 |
| 无需原生 SDK 依赖 | 纯.NET库,无需任何平台特定的原生绑定 |
在.NET MAUI项目中,"不依赖原生 SDK"这一点很重要,因为特定于平台的原生库需要为每个目标单独进行链接步骤。 IronBarcode完全避免了这种复杂性,这意味着同一个NuGet参考可以生成适用于所有三个受支持平台的可用二进制文件,而无需额外的配置。
有关支持的条形码格式的完整列表,请参阅IronBarcode支持的格式文档。 有关生产部署的定价和许可条款,请查看IronBarcode许可页面。
生产中条形码扫描的最佳实践是什么?
将条形码扫描器部署到生产环境中,除了基本的读取调用之外,还需要注意一些其他方面。 以下指南针对.NET MAUI条形码应用程序中最常见的故障点。
选择正确的读取速度。ReadingSpeed.Balanced可以正确处理大多数实际图片。 保留ReadingSpeed.ExtraSlow用于扫描打印文档或用户无法重新捕获的图像。 避免在高音量工作流程中使用ReadingSpeed.ExtraSlow,因为每次扫描都会耗费更长时间。
按预期类型过滤。 如果应用程序只处理QR码,则设置ExpectBarcodeTypes = BarcodeEncoding.QRCode。 限制搜索空间可以减少处理时间,并消除背景图形中存在的其他符号体系造成的误报。
仅在需要时使用ExpectMultipleBarcodes。 将其设置为true总是会导致读取器进行额外的扫描。 对于单条码输入,请保留默认值(false),以便扫描在找到第一个有效代码时立即返回。
优雅地处理空结果。 BarcodeReader.Read()在未检测到条形码时返回空数组,而不是抛出异常。 在访问.Any()并向用户呈现清晰的消息。 带有指导的重试提示("确保条形码光线充足且居中")比通用错误提示更能改善用户体验。
缓存选项对象。 在每次扫描时创建一个BarcodeReaderOptions实例会增加分配。 在类级别构建一次选项,并在多个调用中重复使用。
有关诊断扫描故障和优化性能的更多指导,请参阅IronBarcode故障排除指南和条形码阅读器教程。
下一步计划是什么?
使用IronBarcode构建.NET MAUI条形码扫描器需要安装单个NuGet包,配置平台权限,并调用带有文件路径或流的BarcodeReader.Read()。 同一个 API 可以同时支持 Android、iOS 和 Windows 系统,没有针对特定平台的代码分支。
要进一步扩展应用程序的功能,请参考以下资源:
IronBarcode完整功能列表——所有扫描和生成功能的目录 条形码读取器 API 参考-- 完整的方法和属性文档 MAUI条形码阅读器分步教程——涵盖摄像头集成的详细讲解 MAUI 文档扫描仪指南——文档扫描用例
立即开始免费试用,获取开发许可证密钥,或了解生产部署的许可选项。

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。
相关文章


