.NET MAUI Barcode Scanner for Windows, Android, and iOS
A single .NET MAUI project can scan barcodes on Windows, Android, and iOS — but not with a single SDK. Dynamsoft ships two NuGet packages with different namespaces and APIs: Dynamsoft.DotNet.BarcodeReader.Bundle for Windows desktop (Dynamsoft.CVR / Dynamsoft.DBR) and Dynamsoft.CaptureVisionBundle.Maui for Android and iOS (Dynamsoft.CaptureVisionRouter.Maui). The mobile CameraEnhancer doesn’t exist on Windows, and the desktop API is getter-based where the mobile API exposes properties.
This tutorial merges the Windows desktop sample and the mobile sample into one .csproj that targets all three platforms: per-target-framework PackageReferences, #if guards around the two APIs, one CameraView type resolved to a different handler per platform, and separate page classes so each drawing surface renders reliably.
What you’ll build: One .NET MAUI project that scans barcodes from the camera or image files on Windows, Android, and iOS — SkiaSharp SKCanvasView on iOS and Windows, GraphicsView on Android.
Only need Android and iOS? See the mobile-only MAUI barcode scanner tutorial instead.
Key Takeaways
- One
.csprojtargetsnet10.0-android36.0,net10.0-ios26.0, andnet10.0-windows10.0.19041.0by conditionally including the right NuGet package per target framework and gating the two APIs with#if. - The two Dynamsoft packages are not interchangeable: mobile is property-based (
result.DecodedBarcodesResult.Items,item.Text,item.Location.Points); Windows is getter-based (result.GetDecodedBarcodesResult().GetItems(),item.GetText(),item.GetLocation().points). CameraEnhanceris mobile-only. On Windows the sample runs aMediaCapture/MediaFrameReaderframe loop and calls the desktopCaptureVisionRouterdirectly.- One
CameraViewtype maps to two handlers — a customICameraHandleron Windows and the SDK’s handler on Android/iOS — registered inMauiProgrambehind#if. - Rendering is per-platform: SkiaSharp
SKCanvasViewon iOS (and Windows),GraphicsViewon Android.
How the Two SDKs Differ
The whole architecture follows from one fact: the desktop and mobile packages share a product name, not an API.
| Windows desktop | Android / iOS | |
|---|---|---|
| Package | Dynamsoft.DotNet.BarcodeReader.Bundle 11.6.5000 |
Dynamsoft.CaptureVisionBundle.Maui 3.6.2000 |
| Namespace | Dynamsoft.CVR / Dynamsoft.DBR |
Dynamsoft.CaptureVisionRouter.Maui |
| Decode a file | cvr.Capture(path, PresetTemplate.PT_READ_BARCODES) |
router.Capture(path, EnumPresetTemplate.PT_READ_BARCODES) |
| Read items | result.GetDecodedBarcodesResult().GetItems() |
result.DecodedBarcodesResult.Items |
| Item text / box | item.GetText(), item.GetLocation().points |
item.Text, item.Location.Points |
| Live camera | custom CameraView + MediaCapture |
CameraEnhancer + CameraView |
// Windows desktop — getter-based API in Dynamsoft.CVR / Dynamsoft.DBR
CapturedResult? result = cvr.Capture(imagePath, PresetTemplate.PT_READ_BARCODES);
foreach (var item in result.GetDecodedBarcodesResult().GetItems())
{
Dynamsoft.Core.Point[] points = item.GetLocation().points;
Console.WriteLine(item.GetText());
}
// Android / iOS — property-based API in Dynamsoft.CaptureVisionRouter.Maui
CapturedResult result = router.Capture(filePath, EnumPresetTemplate.PT_READ_BARCODES);
foreach (var item in result.DecodedBarcodesResult.Items)
{
Console.WriteLine(item.Text);
}
Names that differ by one character — PresetTemplate vs EnumPresetTemplate, GetText() vs Text — are why every shared file needs #if WINDOWS / #if ANDROID || IOS around its recognition calls.
Common Developer Questions
How do I use Dynamsoft Barcode Reader in a single .NET MAUI project targeting Windows, Android, and iOS?
Keep one MAUI project but separate the Windows and mobile integration paths behind platform checks, because the desktop and mobile Dynamsoft packages are not identical. This article combines them by conditionally using the right package and page implementation for each target platform.
Why does GraphicsView fail to render text overlays on iOS in .NET MAUI?
GraphicsView can render barcode overlay text unreliably on iOS, while Android has its own stability problems with SKCanvasView. That is why this implementation uses platform-specific page classes and rendering components instead of forcing one drawing surface across Windows, Android, and iOS.
How do I conditionally include NuGet packages per platform in a .csproj file?
Use target-framework conditions in the project file so Android and iOS only receive the MAUI capture package while Windows uses the desktop barcode package. That keeps one project file while still allowing the build to resolve the correct SDK set for each platform.
How do I scan barcodes from a camera in .NET MAUI on Windows?
The mobile CameraEnhancer doesn’t run on Windows. Use a custom View whose handler opens MediaCapture + MediaFrameReader, feed each frame to the desktop CaptureVisionRouter (cvr.Capture(bytes, PresetTemplate.PT_READ_BARCODES)), and draw result.GetDecodedBarcodesResult().GetItems() on an SKCanvasView. The sample’s CameraView.cs + Platforms/Windows/CameraViewHandler.cs do exactly this.
Tested Environment
| Component | Version / target |
|---|---|
| .NET SDK | 10.0.x (maui-android / maui-ios / maui-windows workloads) |
| Microsoft.Maui.Controls | 10.0.20 |
Dynamsoft.CaptureVisionBundle.Maui (mobile) |
3.6.2000 |
Dynamsoft.DotNet.BarcodeReader.Bundle (Windows) |
11.6.5000 |
| Android target | net10.0-android36.0 (API 36), min API 21 |
| iOS target | net10.0-ios26.0, min iOS 15.0 |
| Windows target | net10.0-windows10.0.19041.0 |
| SkiaSharp.Views.Maui.Controls | 3.116.1 |
| CommunityToolkit.Maui / Mvvm | 9.0.1 / 8.2.2 |
The merged examples/WindowsDesktop project is compiled for all three targets by the repository’s GitHub Actions CI. In CI run 42991705357, every target of this project built green:
- Windows —
dotnet build -c Release -f net10.0-windows10.0.19041.0onwindows-latest(job log). - Android —
dotnet build -c Release -f net10.0-android36.0onwindows-latest(job log). - iOS —
dotnet build -c Release -f net10.0-ios26.0 -p:RuntimeIdentifier=iossimulator-arm64onmacos-15with Xcode 26.0.1 (job log).
These are CI build validations, not physical-device runs. Camera preview, permissions, and the SkiaSharp overlay still need to be exercised on a real device or emulator before shipping.
This article is Part 5 in a 5-Part Series.
- Part 1 - Build a .NET MAUI Windows Desktop Barcode Scanner with Live Camera Feed
- Part 2 - How to Build a .NET MAUI Barcode and QR Code Scanner in C#
- Part 3 - How to Build a .NET MAUI Document Scanner App with Capture, Normalize, and Share
- Part 4 - Build a Passport MRZ Scanner for Android and iOS in C# with .NET MAUI
- Part 5 - .NET MAUI Barcode Scanner for Windows, Android, and iOS
See the iOS Barcode Scanner in Action
Prerequisites
- .NET 10 SDK with the
maui-android,maui-ios, andmaui-windowsworkloads. - Visual Studio Code with the .NET MAUI extension, or Visual Studio 2022 on Windows.
- Android SDK (for Android) and Xcode (for iOS, on macOS).
Besides the two Dynamsoft packages, the project uses SkiaSharp.Views.Maui.Controls (the SKCanvasView overlay), CommunityToolkit.Maui, and CommunityToolkit.Mvvm (WeakReferenceMessenger).
Get a 30-day free trial license at dynamsoft.com/customer/license/trialLicense
Step 1: Configure the .csproj File to Target Windows, Android, and iOS
First, remove macOS from the target frameworks to avoid build conflicts when compiling for iOS on macOS:
<PropertyGroup>
<TargetFrameworks>net10.0-android36.0;net10.0-ios26.0</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net10.0-windows10.0.19041.0</TargetFrameworks>
<OutputType>Exe</OutputType>
<RootNamespace>BarcodeQrScanner</RootNamespace>
<UseMaui>true</UseMaui>
<SingleProject>true</SingleProject>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<ApplicationTitle>BarcodeQrScanner</ApplicationTitle>
<ApplicationId>com.companyname.barcodeqrscanner</ApplicationId>
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<ApplicationVersion>1</ApplicationVersion>
<WindowsPackageType>None</WindowsPackageType>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">15.0</SupportedOSPlatformVersion>
<!-- <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">15.0</SupportedOSPlatformVersion> -->
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.19041.0</SupportedOSPlatformVersion>
<TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.19041.0</TargetPlatformMinVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
</PropertyGroup>
Next, conditionally include the mobile-specific NuGet package Dynamsoft.CaptureVisionBundle.Maui:
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0-android36.0' Or '$(TargetFramework)' == 'net10.0-ios26.0'">
<PackageReference Include="Dynamsoft.CaptureVisionBundle.Maui" Version="3.6.2000" />
</ItemGroup>
Include the desktop package Dynamsoft.DotNet.BarcodeReader.Bundle only for the Windows target, as in the sample project:
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0-windows10.0.19041.0'">
<PackageReference Include="Dynamsoft.DotNet.BarcodeReader.Bundle" Version="11.6.5000" />
</ItemGroup>
The UI packages apply to every target — SkiaSharp.Views.Maui.Controls is what provides SKCanvasView on iOS and Windows:
<ItemGroup>
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
<PackageReference Include="SkiaSharp.Views.Maui.Controls" Version="3.116.1" />
<PackageReference Include="CommunityToolkit.Maui" Version="9.0.1" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
</ItemGroup>
Step 2: Isolate Platform-Specific Code with Preprocessor Directives
Use #if directives to isolate code for Android/iOS and Windows:
#if ANDROID || IOS
using Dynamsoft.License.Maui;
#endif
public partial class MainPage : ContentPage
{
#if ANDROID || IOS
class LicenseVerificationListener : ILicenseVerificationListener
{
public void OnLicenseVerified(bool isSuccess, string message)
{
if (!isSuccess)
{
Debug.WriteLine(message);
}
}
}
#endif
public MainPage()
{
InitializeComponent();
#if ANDROID || IOS
LicenseManager.InitLicense("LICENSE-KEY", new LicenseVerificationListener());
#endif
}
}
Register the camera handler and forward lifecycle events
MauiProgram.cs is where the platform split becomes concrete: the same CameraView type resolves to the custom Windows control or the SDK’s mobile control, and lifecycle events are forwarded to the camera page so the preview reopens after backgrounding.
using SkiaSharp.Views.Maui.Controls.Hosting;
using CommunityToolkit.Maui;
using Microsoft.Maui.LifecycleEvents;
using CommunityToolkit.Mvvm.Messaging;
#if WINDOWS
using BarcodeQrScanner.Platforms.Windows;
using BarcodeQrScanner.Controls;
#elif ANDROID || IOS
using Dynamsoft.CameraEnhancer.Maui;
using Dynamsoft.CameraEnhancer.Maui.Handlers;
#endif
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseSkiaSharp()
.UseMauiApp<App>()
.UseMauiCommunityToolkit()
.ConfigureLifecycleEvents(events =>
{
#if ANDROID
events.AddAndroid(android => android
.OnResume((activity) => NotifyPage("Resume"))
.OnStop((activity) => NotifyPage("Stop")));
#elif IOS
events.AddiOS(ios => ios
.WillEnterForeground((app) => NotifyPage("Resume"))
.DidEnterBackground((app) => NotifyPage("Stop")));
#endif
})
.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler(typeof(CameraView), typeof(CameraViewHandler));
});
return builder.Build();
}
private static void NotifyPage(string eventName)
=> WeakReferenceMessenger.Default.Send(new LifecycleEventMessage(eventName));
}
Camera permissions live in the platform manifests: declare android.permission.CAMERA in Platforms/Android/AndroidManifest.xml and NSCameraUsageDescription (plus the photo-library keys) in Platforms/iOS/Info.plist. iOS crashes on the first camera access without the plist key; Android denies the runtime request if the permission is missing from the merged manifest.
Step 3: Choose the Right UI Components per Platform
For mobile, the project keeps four page classes because the two platforms need different drawing surfaces; Windows uses the default PicturePage / CameraPage with SkiaSharp:
- AndroidPicturePage.xaml / AndroidCameraPage.xaml:
GraphicsViewoverlay. - iOSPicturePage.xaml / iOSCameraPage.xaml: SkiaSharp
SKCanvasViewoverlay.
This separation is necessary because:
- Android:
GraphicsViewavoids the crashes and black screens thatSKCanvasViewcauses inside a MAUI camera page. - iOS:
SKCanvasViewresolves the text-rendering failures inGraphicsView.
private async void OnFileButtonClicked(object sender, EventArgs e)
{
try
{
FileResult? photo = null;
if (DeviceInfo.Current.Platform == DevicePlatform.WinUI || DeviceInfo.Current.Platform == DevicePlatform.MacCatalyst)
{
photo = await FilePicker.PickAsync();
}
else if (DeviceInfo.Current.Platform == DevicePlatform.Android || DeviceInfo.Current.Platform == DevicePlatform.iOS)
{
photo = await MediaPicker.CapturePhotoAsync();
}
await LoadPhotoAsync(photo);
}
catch (Exception ex)
{
Debug.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
}
}
private async void OnCameraButtonClicked(object sender, EventArgs e)
{
if (DeviceInfo.Current.Platform == DevicePlatform.Android)
{
await Navigation.PushAsync(new AndroidCameraPage());
}
else if (DeviceInfo.Current.Platform == DevicePlatform.iOS)
{
await Navigation.PushAsync(new iOSCameraPage());
}
else
{
await Navigation.PushAsync(new CameraPage());
}
}
async Task LoadPhotoAsync(FileResult? photo)
{
if (photo == null)
{
return;
}
if (DeviceInfo.Current.Platform == DevicePlatform.Android)
{
await Navigation.PushAsync(new AndroidPicturePage(photo));
}
else if (DeviceInfo.Current.Platform == DevicePlatform.iOS)
{
await Navigation.PushAsync(new iOSPicturePage(photo));
}
else
{
await Navigation.PushAsync(new PicturePage(photo.FullPath));
}
}
Why Platform-Specific Pages Prevent iOS and Android Rendering Failures
While SKCanvasView and GraphicsView are cross-platform in theory, they exhibit critical bugs:
- Android:
SKCanvasViewcauses app crashes and black screens. - iOS:
GraphicsViewfails to render text overlays. Using platform-specific pages ensures stability and performance.
Step 4: Implement Picture and Camera Pages for Android
- Reuse the
PicturePageandCameraPagecode from thehttps://github.com/yushulx/maui-barcode-mrz-document-scanner/tree/main/examples/BarcodeQrScannerasAndroidPicturePageandAndroidCameraPage. -
Add platform directives to
AndroidPicturePage.xaml.cs.#if ANDROID || IOS using Dynamsoft.CaptureVisionRouter.Maui; using Dynamsoft.BarcodeReader.Maui; #endif using SkiaSharp; using System.Diagnostics; using Microsoft.Maui.Graphics.Platform; namespace BarcodeQrScanner; public partial class AndroidPicturePage : ContentPage { #if ANDROID || IOS private CaptureVisionRouter router = new CaptureVisionRouter(); #endif ... async private void LoadImageWithOverlay(FileResult result) { var filePath = result.FullPath; var stream = await result.OpenReadAsync(); float originalWidth = 0; float originalHeight = 0; try { ... #if ANDROID || IOS var streamcopy = await result.OpenReadAsync(); byte[] filestream = new byte[streamcopy.Length]; int offset = 0; while (offset < filestream.Length) { int bytesRead = streamcopy.Read(filestream, offset, filestream.Length - offset); if (bytesRead == 0) break; offset += bytesRead; } streamcopy.Close(); if (offset != filestream.Length) { throw new IOException("Could not read the entire stream."); } CapturedResult capturedResult = router.Capture(filestream, EnumPresetTemplate.PT_READ_BARCODES); DecodedBarcodesResult? barcodeResults = null; if (capturedResult != null) { barcodeResults = capturedResult.DecodedBarcodesResult; } var drawable = new ImageWithOverlayDrawable(barcodeResults, originalWidth, originalHeight, true); OverlayGraphicsView.Drawable = drawable; OverlayGraphicsView.Invalidate(); #endif } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } ... } -
Add directives to
AndroidCameraPage.xaml.cs.namespace BarcodeQrScanner; #if ANDROID || IOS using Dynamsoft.Core.Maui; using Dynamsoft.CaptureVisionRouter.Maui; using Dynamsoft.BarcodeReader.Maui; using Dynamsoft.CameraEnhancer.Maui; using System.Diagnostics; using CommunityToolkit.Mvvm.Messaging; public partial class AndroidCameraPage : ContentPage, ICapturedResultReceiver, ICompletionListener { ... } #endif
Step 5: Implement Picture and Camera Pages for iOS
As mentioned earlier, the GraphicsView has some UI rendering issues. To resolve this issue, we use SKCanvasView instead.
Build the iOS Picture Page with SKCanvasView
-
Add the following layout code to
iOSPicturePage.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="BarcodeQrScanner.iOSPicturePage" xmlns:skia="clr-namespace:SkiaSharp.Views.Maui.Controls;assembly=SkiaSharp.Views.Maui.Controls" Title="iOSPicturePage"> <ContentPage.Content> <Grid> <skia:SKCanvasView x:Name="canvasView" HorizontalOptions="Fill" VerticalOptions="Fill" PaintSurface="OnCanvasViewPaintSurface"/> <Label FontSize="18" FontAttributes="Bold" x:Name="ResultLabel" Text="" TextColor="Red" HorizontalOptions="Center" VerticalOptions="Center"/> </Grid> </ContentPage.Content> </ContentPage> -
In
iOSPicturePage.xaml.cs, follow these steps:-
Decode an image file to
SKBitmap:var stream = await fileResult.OpenReadAsync(); bitmap = SKBitmap.Decode(stream); -
Read barcodes from the image stream:
private CaptureVisionRouter router = new CaptureVisionRouter(); stream = await fileResult.OpenReadAsync(); byte[] filestream = new byte[stream.Length]; int offset = 0; while (offset < filestream.Length) { int bytesRead = stream.Read(filestream, offset, filestream.Length - offset); if (bytesRead == 0) break; offset += bytesRead; } stream.Close(); if (offset != filestream.Length) { throw new IOException("Could not read the entire stream."); } result = router.Capture(filestream, EnumPresetTemplate.PT_READ_BARCODES); -
Render the bitmap and barcode results on
SKCanvasView:void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { if (!isDataReady) { return; } SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); if (bitmap != null) { var imageCanvas = new SKCanvas(bitmap); float textSize = 28; float StrokeWidth = 4; if (DeviceInfo.Current.Platform == DevicePlatform.Android || DeviceInfo.Current.Platform == DevicePlatform.iOS) { textSize = (float)(18 * DeviceDisplay.MainDisplayInfo.Density); StrokeWidth = 4; } SKPaint skPaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Blue, StrokeWidth = StrokeWidth, }; SKPaint textPaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Red, StrokeWidth = StrokeWidth, }; SKFont font = new SKFont() { Size = textSize }; #if ANDROID || IOS if (isDataReady) { if (result != null) { ResultLabel.Text = ""; DecodedBarcodesResult? barcodesResult = result.DecodedBarcodesResult; if (barcodesResult != null) { var items = barcodesResult.Items; foreach (var barcodeItem in items) { Microsoft.Maui.Graphics.Point[] points = barcodeItem.Location.Points; imageCanvas.DrawText(barcodeItem.Text, (float)points[0].X, (float)points[0].Y, SKTextAlign.Left, font, textPaint); imageCanvas.DrawLine((float)points[0].X, (float)points[0].Y, (float)points[1].X, (float)points[1].Y, skPaint); imageCanvas.DrawLine((float)points[1].X, (float)points[1].Y, (float)points[2].X, (float)points[2].Y, skPaint); imageCanvas.DrawLine((float)points[2].X, (float)points[2].Y, (float)points[3].X, (float)points[3].Y, skPaint); imageCanvas.DrawLine((float)points[3].X, (float)points[3].Y, (float)points[0].X, (float)points[0].Y, skPaint); } } } else { ResultLabel.Text = "No 1D/2D barcode found"; } } #endif float scale = Math.Min((float)info.Width / bitmap.Width, (float)info.Height / bitmap.Height); float x = (info.Width - scale * bitmap.Width) / 2; float y = (info.Height - scale * bitmap.Height) / 2; SKRect destRect = new SKRect(x, y, x + scale * bitmap.Width, y + scale * bitmap.Height); canvas.DrawBitmap(bitmap, destRect); } }
-
Build the iOS Camera Page with Live Barcode Overlay
-
Add the following layout code to
iOSCameraPage.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="BarcodeQrScanner.iOSCameraPage" xmlns:skia="clr-namespace:SkiaSharp.Views.Maui.Controls;assembly=SkiaSharp.Views.Maui.Controls" Title="iOSCameraPage"> <Grid x:Name="MainGrid" Margin="0"> <skia:SKCanvasView x:Name="canvasView" Margin="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/> </Grid> </ContentPage>Note: Do not place the camera preview control here. Instead, add it dynamically in the code-behind file to avoid build failures.
-
In
iOSCameraPage.xaml.cs, implement the camera preview and barcode scanning:-
Initialize the camera preview and barcode scanner. Insert the camera preview control into
MainGridbelow theSKCanvasView. UseOnCanvasViewPaintSurfaceto render barcode results.public iOSCameraPage() { InitializeComponent(); canvasView.PaintSurface += OnCanvasViewPaintSurface; if (DeviceInfo.Platform == DevicePlatform.Android || DeviceInfo.Platform == DevicePlatform.iOS) { CameraPreview = new Dynamsoft.CameraEnhancer.Maui.CameraView(); MainGrid.Children.Insert(0, CameraPreview); } enhancer = new CameraEnhancer(); router = new CaptureVisionRouter(); router.SetInput(enhancer); router.AddResultReceiver(this); WeakReferenceMessenger.Default.Register<LifecycleEventMessage>(this, (r, message) => { if (message.EventName == "Resume") { if (this.Handler != null && enhancer != null) { enhancer.Open(); } } else if (message.EventName == "Stop") { enhancer?.Close(); } }); } -
Receive barcode results in a callback function and trigger
SKCanvasViewto render them.public void OnDecodedBarcodesReceived(DecodedBarcodesResult result) { if (imageWidth == 0 && imageHeight == 0) { IntermediateResultManager manager = router.GetIntermediateResultManager(); ImageData data = manager.GetOriginalImage(result.OriginalImageHashId); imageWidth = data.Width; imageHeight = data.Height; } lock (_lockObject) { _barcodeResult = result; CameraPreview.GetDrawingLayer(EnumDrawingLayerId.DLI_DBR).Visible = false; MainThread.BeginInvokeOnMainThread(() => { canvasView.InvalidateSurface(); }); } } -
Render the result overlay in the
OnCanvasViewPaintSurfaceevent handler.void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { double width = canvasView.Width; double height = canvasView.Height; var mainDisplayInfo = DeviceDisplay.MainDisplayInfo; var orientation = mainDisplayInfo.Orientation; var rotation = mainDisplayInfo.Rotation; var density = mainDisplayInfo.Density; width *= density; height *= density; double scale, widthScale, heightScale, scaledWidth, scaledHeight; double previewWidth, previewHeight; if (orientation == DisplayOrientation.Portrait) { previewWidth = imageWidth; previewHeight = imageHeight; } else { previewWidth = imageHeight; previewHeight = imageWidth; } widthScale = previewWidth / width; heightScale = previewHeight / height; scale = widthScale < heightScale ? widthScale : heightScale; scaledWidth = previewWidth / scale; scaledHeight = previewHeight / scale; SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); SKPaint skPaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Blue, StrokeWidth = 4, }; SKPaint textPaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Red, StrokeWidth = 4, }; float textSize = 18; SKFont font = new SKFont() { Size = textSize }; lock (_lockObject) { if (_barcodeResult != null) { DecodedBarcodesResult? barcodesResult = _barcodeResult; if (barcodesResult != null) { var items = barcodesResult.Items; if (items != null) { foreach (var barcodeItem in items) { Microsoft.Maui.Graphics.Point[] points = barcodeItem.Location.Points; float x1 = (float)(points[0].X / scale); float y1 = (float)(points[0].Y / scale); float x2 = (float)(points[1].X / scale); float y2 = (float)(points[1].Y / scale); float x3 = (float)(points[2].X / scale); float y3 = (float)(points[2].Y / scale); float x4 = (float)(points[3].X / scale); float y4 = (float)(points[3].Y / scale); if (widthScale < heightScale) { y1 = (float)(y1 - (scaledHeight - height) / 2); y2 = (float)(y2 - (scaledHeight - height) / 2); y3 = (float)(y3 - (scaledHeight - height) / 2); y4 = (float)(y4 - (scaledHeight - height) / 2); } else { x1 = (float)(x1 - (scaledWidth - width) / 2); x2 = (float)(x2 - (scaledWidth - width) / 2); x3 = (float)(x3 - (scaledWidth - width) / 2); x4 = (float)(x4 - (scaledWidth - width) / 2); } canvas.DrawText(barcodeItem.Text, x1, y1 - 10, SKTextAlign.Left, font, textPaint); canvas.DrawLine(x1, y1, x2, y2, skPaint); canvas.DrawLine(x2, y2, x3, y3, skPaint); canvas.DrawLine(x3, y3, x4, y4, skPaint); canvas.DrawLine(x4, y4, x1, y1, skPaint); } } } } } }
-
Common Issues & Edge Cases
- iOS camera preview not appearing: If you declare the
CameraViewin XAML, the iOS build may fail with a linker error. Always add theDynamsoft.CameraEnhancer.Maui.CameraViewcontrol dynamically in code-behind usingMainGrid.Children.Insert(0, CameraPreview). - Android black screen with SkiaSharp:
SKCanvasViewis not stable on Android within MAUI camera pages. UseGraphicsViewwith a customIDrawablefor Android overlays to avoid rendering crashes. - Barcode coordinates misaligned on rotated device: The overlay scale calculation must account for display orientation (
DisplayOrientation.Portraitvs.Landscape). SwapimageWidth/imageHeightwhen the device is in landscape mode and recalculate the offset to reposition points correctly. - Black preview after backgrounding: the lifecycle events weren’t forwarded. Wire
OnResume/OnStopon Android andWillEnterForeground/DidEnterBackgroundon iOS as shown in Step 2 —enhancer.Close()on stop andenhancer.Open()on resume.
Step 6: Run the .NET MAUI Barcode Scanner on Windows, Android, and iOS
-
In Visual Studio Code, click the curly brackets icon at the bottom.

-
Select the target device.

-
Press
F5to run the application.
Source Code
The complete sample on GitHub — examples/WindowsDesktop is the merged project that targets Windows, Android, and iOS (the folder name predates the merge). The mobile-only project it borrows its pages from is examples/BarcodeQrScanner.