### UseBarcodeScanning extension and required MauiProgram setup Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/extensions.md Registers the CameraViewHandler for CameraView on the MAUI app builder. The second block shows the required initialization in MauiProgram.CreateMauiApp(); without calling UseBarcodeScanning, CameraView has no handler and no camera starts. ```csharp public static MauiAppBuilder UseBarcodeScanning(this MauiAppBuilder builder) { return builder.ConfigureMauiHandlers(handlers => handlers.AddHandler()); } ``` ```csharp public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp() .ConfigureFonts(fonts => { /* ... */ }) .UseBarcodeScanning(); return builder.Build(); } ``` -------------------------------- ### CameraFacing Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the camera facing direction (front or back). ```APIDOC ## CameraFacing ### Description Gets or sets the camera facing direction (front or back). ### Property ```csharp public CameraFacing CameraFacing { get; set; } ``` ### Type CameraFacing ### Default Value CameraFacing.Back ### Binding Mode TwoWay ``` -------------------------------- ### Load Raw Asset with FileSystem.OpenAppPackageFileAsync Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/BarcodeScanning.Test/Resources/Raw/AboutAssets.txt Loads a raw asset file from the app package using the Essentials FileSystem.OpenAppPackageFileAsync method. The example reads the file contents into a string; the stream and reader are disposed automatically. ```csharp async Task LoadMauiAsset() { using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt"); using var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); } ``` -------------------------------- ### TorchOn Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether the torch is on. ```APIDOC ## TorchOn ### Description Gets or sets a value indicating whether the torch is on. ### Property ```csharp public bool TorchOn { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### CaptureQuality Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the capture quality for image capture. ```APIDOC ## CaptureQuality ### Description Gets or sets the capture quality for image capture. ### Property ```csharp public CaptureQuality CaptureQuality { get; set; } ``` ### Type CaptureQuality ### Default Value CaptureQuality.Medium ### Binding Mode TwoWay ``` -------------------------------- ### OnImageCapturedCommand Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the command that is invoked when an image is captured. This is an MVVM alternative to the OnImageCaptured event. ```APIDOC ## OnImageCapturedCommand ### Description Gets or sets the command that is invoked when an image is captured. This is an MVVM alternative to the OnImageCaptured event. ### Property ```csharp public ICommand OnImageCapturedCommand { get; set; } ``` ### Type ICommand ### Default Value null ### Binding Mode Default ### Remarks Invoked with the captured PlatformImage when CanExecute(...) is true. ``` -------------------------------- ### Draw captured image on canvas Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/event-args.md Example of drawing the captured image on a canvas, taken from the test app. It draws the image at a scaled size. ```csharp public void Draw(ICanvas canvas, RectF dirtyRect) { if (image is not null) canvas.DrawImage(image, 10, 10, image.Width / 8, image.Height / 8); } ``` -------------------------------- ### RequestZoomFactor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the requested zoom factor. ```APIDOC ## RequestZoomFactor ### Description Gets or sets the requested zoom factor. ### Property ```csharp public float RequestZoomFactor { get; set; } ``` ### Type float ### Default Value -1f ### Binding Mode TwoWay ``` -------------------------------- ### BarcodeSymbologies Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the barcode symbologies to scan for. ```APIDOC ## BarcodeSymbologies ### Description Gets or sets the barcode symbologies to scan for. ### Property ```csharp public BarcodeFormats BarcodeSymbologies { get; set; } ``` ### Type BarcodeFormats ### Default Value BarcodeFormats.All ### Binding Mode TwoWay ``` -------------------------------- ### PoolingInterval Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the pooling interval in milliseconds. ```APIDOC ## PoolingInterval ### Description Gets or sets the pooling interval in milliseconds. ### Property ```csharp public int PoolingInterval { get; set; } ``` ### Type int ### Default Value 0 ### Binding Mode TwoWay ``` -------------------------------- ### CameraEnabled Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Disables or enables the camera. Setting to true starts the capture session, false stops it. ```APIDOC ## CameraEnabled ### Description Disables or enables the camera. Setting to `true` starts the capture session via `CameraManager.Start()`, which re-applies resolution, camera, symbologies, and torch. Setting to `false` stops and unbinds the session. ### Property - **Type**: `bool` - **Default**: `false` - **BindingMode**: TwoWay ### Behavior - `true` starts the capture session. - `false` stops and unbinds it. - Recommended `true` in `OnAppearing()`, `false` in `OnDisappearing()`. ### Code Example ```csharp public static readonly BindableProperty CameraEnabledProperty = BindableProperty.Create(nameof(CameraEnabled) , typeof(bool) , typeof(CameraView) , false , BindingMode.TwoWay , propertyChanged: (bindable, value, newValue) => ((CameraView)bindable).CameraEnabled = (bool)newValue); public bool CameraEnabled { get => (bool)GetValue(CameraEnabledProperty); set => SetValue(CameraEnabledProperty, value); } ``` ``` -------------------------------- ### CaptureNextFrame Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether to capture the next frame. ```APIDOC ## CaptureNextFrame ### Description Gets or sets a value indicating whether to capture the next frame. ### Property ```csharp public bool CaptureNextFrame { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### OnDetectionFinishedCommand Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the command that is invoked when barcode detection finishes. This is an MVVM alternative to the OnDetectionFinished event. ```APIDOC ## OnDetectionFinishedCommand ### Description Gets or sets the command that is invoked when barcode detection finishes. This is an MVVM alternative to the OnDetectionFinished event. ### Property ```csharp public ICommand OnDetectionFinishedCommand { get; set; } ``` ### Type ICommand ### Default Value null ### Binding Mode Default ### Remarks Invoked with an IReadOnlySet when CanExecute(...) is true. ``` -------------------------------- ### CameraEnabled Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether the camera is enabled. ```APIDOC ## CameraEnabled ### Description Gets or sets a value indicating whether the camera is enabled. ### Property ```csharp public bool CameraEnabled { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### ForceFrameCapture Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether to force frame capture. ```APIDOC ## ForceFrameCapture ### Description Gets or sets a value indicating whether to force frame capture. ### Property ```csharp public bool ForceFrameCapture { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### AimMode Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether aim mode is enabled. ```APIDOC ## AimMode ### Description Gets or sets a value indicating whether aim mode is enabled. ### Property ```csharp public bool AimMode { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### Handle OnImageCaptured with disposal Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/event-args.md Example of handling the OnImageCaptured event with proper disposal. It disposes the previous frame, stores the new image for drawing, and disposes it again when the page disappears. ```csharp private PlatformImage? _lastFrame; private void CameraView_OnImageCaptured(object sender, OnImageCapturedEventArg e) { _lastFrame?.Dispose(); _lastFrame = e.Image; // keep a reference for drawing Graphics.Invalidate(); } protected override void OnDisappearing() { base.OnDisappearing(); _lastFrame?.Dispose(); _lastFrame = null; } ``` -------------------------------- ### CameraEnabled bindable property Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Bindable property and CLR wrapper for CameraEnabled. When true, starts the capture session via CameraManager.Start() (re-applying resolution, camera, symbologies, and torch); when false, stops and unbinds it. Recommended true in OnAppearing() and false in OnDisappearing(). ```csharp public static readonly BindableProperty CameraEnabledProperty = BindableProperty.Create(nameof(CameraEnabled) , typeof(bool) , typeof(CameraView) , false , BindingMode.TwoWay , propertyChanged: (bindable, value, newValue) => ((CameraView)bindable).CameraEnabled = (bool)newValue); /// /// Disables or enables camera. /// public bool CameraEnabled { get => (bool)GetValue(CameraEnabledProperty); set => SetValue(CameraEnabledProperty, value); } ``` -------------------------------- ### ViewfinderMode Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether viewfinder mode is enabled. ```APIDOC ## ViewfinderMode ### Description Gets or sets a value indicating whether viewfinder mode is enabled. ### Property ```csharp public bool ViewfinderMode { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### MinZoomFactor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets the minimum zoom factor. This is a status property that is updated by the control. ```APIDOC ## MinZoomFactor ### Description Gets the minimum zoom factor. This is a status property that is updated by the control. ### Property ```csharp public float MinZoomFactor { get; } ``` ### Type float ### Default Value -1f ### Binding Mode OneWayToSource (status) ``` -------------------------------- ### ForceInverted Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether to force inverted barcode detection. ```APIDOC ## ForceInverted ### Description Gets or sets a value indicating whether to force inverted barcode detection. ### Property ```csharp public bool ForceInverted { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### Handle OnDetectionFinished in code-behind Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/event-args.md Example of handling the OnDetectionFinished event in code-behind. It checks for an empty result set and updates a label with the first barcode's display value. ```csharp private void CameraView_OnDetectionFinished(object sender, OnDetectionFinishedEventArg e) { if (e.BarcodeResults.Count == 0) return; var first = e.BarcodeResults.First(); ResultLabel.Text = first.DisplayValue; } ``` -------------------------------- ### AimMode Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a boolean value that disables or enables aim mode. When enabled, only barcodes in the center of the preview are detected. ```APIDOC ## AimMode ### Description Disables or enables aim mode. When enabled only barcode that is in the center of the preview will be detected. ### Property `public bool AimMode` ### BindableProperty `public static readonly BindableProperty AimModeProperty` ### Default Value `false` ### Binding Mode `TwoWay` ### Behavior Overlays the aim indicator (dot in `AimIndicatorColor`; 25px Android, 8pt `CAShapeLayer` iOS/macOS, 20px `Border` Windows) and reports only barcodes whose `PreviewBoundingBox` contains the preview center. ``` -------------------------------- ### CaptureNextFrame Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a boolean value that captures the next frame from the camera feed. When set to true, the next frame with at least one barcode result is captured and emitted. ```APIDOC ## CaptureNextFrame ### Description Captures the next frame from the camera feed. ### Property `public bool CaptureNextFrame` ### BindableProperty `public static readonly BindableProperty CaptureNextFrameProperty` ### Default Value `false` ### Binding Mode `TwoWay` ### Behavior When `true`, the next frame that yields at least one barcode result is captured and emitted through `OnImageCaptured`/`OnImageCapturedCommand` as a `PlatformImage`. Auto-reset to `false` after capture to prevent leaks. The image comes from the original camera feed and can differ from the on-screen preview. ``` -------------------------------- ### ForceFrameCapture Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a boolean value that forces the capture of camera frames regardless of barcode detection. The flag is not automatically disabled after capture. ```APIDOC ## ForceFrameCapture ### Description Forces the capture of camera frames regardless of whether a barcode is detected or not. Is not automatically disabled after the frame is captured. ### Property `public bool ForceFrameCapture` ### BindableProperty `public static readonly BindableProperty ForceFrameCaptureProperty` ### Default Value `false` ### Binding Mode `TwoWay` ### Behavior Same capture path as `CaptureNextFrame`, but the frame is captured on every camera frame even with zero detections, and the flag is not auto-reset. ``` -------------------------------- ### ViewfinderMode Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a boolean value that disables or enables viewfinder mode. When enabled, only barcodes visible in the preview are detected. ```APIDOC ## ViewfinderMode ### Description Disables or enables viewfinder mode. When enabled only barcode that is visible in the preview will be detected. ### Property `public bool ViewfinderMode` ### BindableProperty `public static readonly BindableProperty ViewfinderModeProperty` ### Default Value `false` ### Binding Mode `TwoWay` ### Behavior Reports only barcodes fully contained inside the preview rectangle (`_previewRect.Contains(barcodeResult.PreviewBoundingBox)` on each platform). ``` -------------------------------- ### CameraView Constructor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Initializes a new instance of the CameraView class. No parameters are required; behavior is configured via bindable properties. ```APIDOC ## CameraView Constructor ### Description Initializes a new instance of the CameraView class. No parameters are required; behavior is configured via bindable properties. ### Method Constructor ### Signature ```csharp public CameraView() ``` ### Parameters None. ### Remarks Initializes pooling state. ``` -------------------------------- ### Initialize BarcodeScanning in MauiProgram.cs Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/index.md Initialize the BarcodeScanning.Native.Maui library in MauiProgram.cs by adding the UseBarcodeScanning extension method to the builder chain. ```csharp var builder = MauiApp.CreateBuilder(); builder .UseMauiApp() .UseBarcodeScanning(); // Extensions.UseBarcodeScanning ``` -------------------------------- ### CameraFacing Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Bindable property that selects the back or front camera. ```APIDOC ## [PROPERTY] CameraFacing ### Description Selects the back or front camera. Default value is Back Camera. ### Property `public CameraFacing CameraFacing { get; set; }` ### Type `CameraFacing` ### Default Value `CameraFacing.Back` ### Binding Mode TwoWay ### Platform Behavior - **Android**: `CameraSelector.DefaultFrontCamera`/`DefaultBackCamera` - **iOS/macOS**: Back camera falls back through `BuiltInTripleCamera` → `BuiltInDualWideCamera` → `BuiltInDualCamera` → `BuiltInWideAngleCamera`, then any default video device - **Windows**: First video color source whose `EnclosureLocation.Panel` matches ``` -------------------------------- ### MauiAsset Build Action for Raw Assets Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/BarcodeScanning.Test/Resources/Raw/AboutAssets.txt Declares the MauiAsset build action in the .csproj file to automatically deploy raw assets from the Resources\Raw directory and its subdirectories. The LogicalName metadata preserves the relative directory structure and file name. ```xml ``` -------------------------------- ### Scan from a picked file using FilePicker and Methods.ScanFromImageAsync Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Picks an image file with FilePicker.Default.PickAsync, then scans it with Methods.ScanFromImageAsync. Iterates over the returned BarcodeResult set and prints each barcode format and display value to the console. ```csharp var file = await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Pick an image with a barcode" }); if (file is not null) { IReadOnlySet results = await Methods.ScanFromImageAsync(file); foreach (var result in results) { Console.WriteLine($"{result.BarcodeFormat}: {result.DisplayValue}"); } } ``` -------------------------------- ### TapToFocusEnabled Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether tap-to-focus is enabled. ```APIDOC ## TapToFocusEnabled ### Description Gets or sets a value indicating whether tap-to-focus is enabled. ### Property ```csharp public bool TapToFocusEnabled { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### CameraView constructor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Parameterless constructor for CameraView. Behavior is configured via bindable properties; initializes pooling state. ```csharp public CameraView() ``` -------------------------------- ### PauseScanning Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether scanning is paused. ```APIDOC ## PauseScanning ### Description Gets or sets a value indicating whether scanning is paused. ### Property ```csharp public bool PauseScanning { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### CreatePlatformView per target framework Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view-handler.md The CreatePlatformView override is defined per target framework and selected at compile time. The table lists the source file and implementation for each framework. Plain net10.0 throws PlatformNotSupportedException. ```csharp _cameraManager = new CameraManager(VirtualView, Context); ArgumentNullException.ThrowIfNull(_cameraManager.BarcodeView); return _cameraManager.BarcodeView; ``` ```csharp _cameraManager = new CameraManager(VirtualView); ... return _cameraManager.BarcodeView; ``` ```csharp _cameraManager = new CameraManager(VirtualView); ... return _cameraManager.BarcodeView; ``` ```csharp _cameraManager = null; throw new PlatformNotSupportedException(); ``` -------------------------------- ### MaxZoomFactor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets the maximum zoom factor. This is a status property that is updated by the control. ```APIDOC ## MaxZoomFactor ### Description Gets the maximum zoom factor. This is a status property that is updated by the control. ### Property ```csharp public float MaxZoomFactor { get; } ``` ### Type float ### Default Value -1f ### Binding Mode OneWayToSource (status) ``` -------------------------------- ### CameraViewHandler CameraCommandMapper empty map Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view-handler.md Empty command mapper; no commands are registered for the handler. ```csharp public static readonly CommandMapper CameraCommandMapper = new() { }; ``` -------------------------------- ### UseBarcodeScanning() - Register CameraViewHandler Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/configuration.md Required for the CameraView control to work. Registers the CameraViewHandler via ConfigureMauiHandlers; without it, CameraView has no handler. This is the only app-builder registration method; no other configuration files or environment variables are used. ```csharp var builder = MauiApp.CreateBuilder(); builder .UseMauiApp() .UseBarcodeScanning(); ``` -------------------------------- ### CurrentZoomFactor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets the current zoom factor. This is a status property that is updated by the control. ```APIDOC ## CurrentZoomFactor ### Description Gets the current zoom factor. This is a status property that is updated by the control. ### Property ```csharp public float CurrentZoomFactor { get; } ``` ### Type float ### Default Value -1f ### Binding Mode OneWayToSource (status) ``` -------------------------------- ### CameraFacing enum Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/types.md Selects the camera. Used by CameraView.CameraFacing with default Back. Platform resolution is described in camera-view.md. ```csharp public enum CameraFacing { Back = 0, Front = 1 } ``` -------------------------------- ### Scan from raw bytes with empty-result handling Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Loads image bytes, scans them with Methods.ScanFromImageAsync, and handles an empty result set (no barcode found or undecodable image on Android/iOS). Finds the first QR code result and opens its RawValue with Launcher.OpenAsync. Catches exceptions for decode failures on Windows and bad URLs. ```csharp byte[] imageBytes = await LoadImageBytesAsync(); try { var results = await Methods.ScanFromImageAsync(imageBytes); if (results.Count == 0) { // No barcode found (or image could not be decoded on Android/iOS — // an undecodable image yields an empty set there). return; } var qr = results.First(r => r.BarcodeFormat.HasFlag(BarcodeFormats.QRCode)); await Launcher.OpenAsync(qr.RawValue); } catch (Exception ex) // decode failures on Windows and bad URLs { await DisplayAlertAsync("Scan failed", ex.Message, "OK"); } ``` -------------------------------- ### CameraViewHandler constructor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view-handler.md Constructor passes the static mappers to the base ViewHandler. ```csharp public CameraViewHandler() : base(CameraViewMapper, CameraCommandMapper) ``` -------------------------------- ### MVVM binding with photo capture Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Shows how to use CameraView with MVVM binding, including commands for detection finished and image captured. The XAML sets up the CameraView with commands and properties, and the ViewModel handles the commands, saving the captured image and disposing it. ```xml ``` ```csharp public class ScanViewModel { public ICommand DetectionFinishedCommand { get; } public ICommand ImageCapturedCommand { get; } public ScanViewModel() { DetectionFinishedCommand = new Command>(set => { if (set.Count == 0) return; // no barcode this round — keep scanning Status = $"Detected: {string.Join(", ", set.Select(r => r.DisplayValue))}"; }); ImageCapturedCommand = new Command(image => { try { SaveImage(image); } // consumer must dispose the PlatformImage finally { image.Dispose(); } }); } } ``` -------------------------------- ### Code-behind usage of CameraView Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Shows how to use CameraView in code-behind, subscribing to the OnDetectionFinished event, enabling the camera on appearing, and disabling on disappearing. The event handler updates a label with the first barcode result. ```csharp public partial class ScanPage : ContentPage { public ScanPage() { InitializeComponent(); Barcode.OnDetectionFinished += CameraView_OnDetectionFinished; } protected override void OnAppearing() { base.OnAppearing(); Barcode.CameraEnabled = true; } protected override void OnDisappearing() { base.OnDisappearing(); Barcode.CameraEnabled = false; } private void CameraView_OnDetectionFinished(object sender, OnDetectionFinishedEventArg e) { if (e.BarcodeResults.Count > 0) { var first = e.BarcodeResults.First(); ResultLabel.Text = $"{first.DisplayValue} ({first.BarcodeFormat})"; } } } ``` -------------------------------- ### VibrationOnDetected Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets a value indicating whether vibration should occur when a barcode is detected. ```APIDOC ## VibrationOnDetected ### Description Gets or sets a value indicating whether vibration should occur when a barcode is detected. ### Property ```csharp public bool VibrationOnDetected { get; set; } ``` ### Type bool ### Default Value false ### Binding Mode TwoWay ``` -------------------------------- ### CameraFacing bindable property Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Bindable property for selecting the back or front camera. Default is CameraFacing.Back. On Android it uses CameraSelector.DefaultFrontCamera or DefaultBackCamera; on iOS/macOS it falls back through BuiltInTripleCamera, BuiltInDualWideCamera, BuiltInDualCamera, BuiltInWideAngleCamera, then any default video device; on Windows it picks the first video color source whose EnclosureLocation.Panel matches. ```csharp public static readonly BindableProperty CameraFacingProperty = BindableProperty.Create(nameof(CameraFacing) , typeof(CameraFacing) , typeof(CameraView) , CameraFacing.Back , BindingMode.TwoWay , propertyChanged: (bindable, value, newValue) => ((CameraView)bindable).CameraFacing = (CameraFacing)newValue); /// /// Select Back or Front camera. /// Default value is Back Camera. /// public CameraFacing CameraFacing { get => (CameraFacing)GetValue(CameraFacingProperty); set => SetValue(CameraFacingProperty, value); } ``` -------------------------------- ### DeviceSwitchZoomFactor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets the zoom factor for device switch. This is a status property that is updated by the control (iOS only). ```APIDOC ## DeviceSwitchZoomFactor ### Description Gets the zoom factor for device switch. This is a status property that is updated by the control (iOS only). ### Property ```csharp public float[] DeviceSwitchZoomFactor { get; } ``` ### Type float[] ### Default Value Array.Empty() ### Binding Mode OneWayToSource (status, iOS) ``` -------------------------------- ### Invoke OnDetectionFinished with event args Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/event-args.md Shows how the OnDetectionFinished event is raised with the OnDetectionFinishedEventArg payload. This is created inside CameraView.TriggerOnDetectionFinished (line 404). ```csharp OnDetectionFinished?.Invoke(this, new OnDetectionFinishedEventArg { BarcodeResults = barcodeResults }); ``` -------------------------------- ### UseBarcodeScanning Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/extensions.md Registers the CameraViewHandler for CameraView on the MAUI app builder, enabling the CameraView control. This is the mandatory initialization step for barcode scanning. ```APIDOC ## UseBarcodeScanning ### Description Registers the `CameraViewHandler` for `CameraView` on the MAUI app builder, enabling the `CameraView` control. This is the mandatory initialization step for barcode scanning. ### Method Extension method on `MauiAppBuilder`. ### Signature `public static MauiAppBuilder UseBarcodeScanning(this MauiAppBuilder builder)` ### Parameters - **builder** (`MauiAppBuilder`) - Required - The MAUI app builder from `MauiApp.CreateBuilder()`. ### Returns `MauiAppBuilder` - the same builder with the handler registration applied, supporting fluent chaining. ### Behavior Registers `CameraViewHandler` as the MAUI handler for `CameraView`. Without this, `CameraView` has no handler and no camera starts. ### Example ```csharp public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp() .ConfigureFonts(fonts => { /* ... */ }) .UseBarcodeScanning(); return builder.Build(); } ``` ``` -------------------------------- ### Request permission with Methods.AskForRequiredPermissionAsync() Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/README.md Call this method to ask the user for the required camera permission on iOS/macOS. Must be invoked in your code after adding the usage description. ```csharp await Methods.AskForRequiredPermissionAsync(); ``` -------------------------------- ### AimIndicatorColor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the color of the aim indicator. This property is read-only from outside the class (private set). ```APIDOC ## AimIndicatorColor ### Description Gets or sets the color of the aim indicator. This property is read-only from outside the class (private set). ### Property ```csharp public Color AimIndicatorColor { get; private set; } ``` ### Type Color ### Default Value new Color(255, 0, 0, 150) ### Binding Mode OneTime, private set ``` -------------------------------- ### AskForRequiredPermissionAsync() Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Requests the required permission (e.g., camera) before using the camera for barcode scanning. ```APIDOC ## AskForRequiredPermissionAsync() ### Description Requests the required permission (e.g., camera) before using the camera for barcode scanning. ### Method AskForRequiredPermissionAsync ### Returns bool - True if permission is granted, false otherwise. ### Example ```csharp if (await Methods.AskForRequiredPermissionAsync()) { Barcode.CameraEnabled = true; } ``` ``` -------------------------------- ### Request required permission before enabling camera Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Calls Methods.AskForRequiredPermissionAsync() to request the necessary permission. If granted, sets Barcode.CameraEnabled to true to enable the camera. ```csharp if (await Methods.AskForRequiredPermissionAsync()) { Barcode.CameraEnabled = true; } ``` -------------------------------- ### AskForRequiredPermissionAsync signature Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Checks camera permission via Permissions.CheckStatusAsync() and, if not granted, requests it. Returns true when already granted or granted after the request, false otherwise, swallowing any exception. No parameters are required. ```csharp public static async Task AskForRequiredPermissionAsync() ``` -------------------------------- ### CameraView.AimIndicatorColor Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Gets or sets the color of the aim indicator in the camera view. Default is semi-transparent red. The property uses BindingMode.OneTime by default. ```APIDOC ## CameraView.AimIndicatorColor ### Description Gets or sets the color of the aim indicator in the camera view. Default is semi-transparent red. The property uses BindingMode.OneTime by default. ### Property `public Color AimIndicatorColor` ### Bindable Property `AimIndicatorColorProperty` ### Type `Color` ### Default Value `Color(255, 0, 0, 150)` (semi-transparent red) ### Binding Mode `OneTime` ### Remarks - The value is read when the native overlay is created (Android canvas circle, iOS/macOS `CAShapeLayer`, Windows `Border`). - The setter is private. ``` -------------------------------- ### Status zoom bindable properties (CurrentZoomFactor, MinZoomFactor, MaxZoomFactor, DeviceSwitchZoomFactor) Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Status bindable properties written back by the platform using BindingMode.OneWayToSource. CurrentZoomFactor, MinZoomFactor, and MaxZoomFactor are floats defaulting to -1f; DeviceSwitchZoomFactor is a float[] defaulting to Array.Empty() and is populated only on iOS/macOS. Values come from platform-specific sources such as IZoomState.ZoomRatio, AVCaptureDevice.VideoZoomFactor, and ZoomControl.Value. ```csharp public static readonly BindableProperty CurrentZoomFactorProperty = BindableProperty.Create(nameof(CurrentZoomFactor) , typeof(float) , typeof(CameraView) , -1f , BindingMode.OneWayToSource); /// /// Returns current zoom factor value. /// public float CurrentZoomFactor { get => (float)GetValue(CurrentZoomFactorProperty); set => SetValue(CurrentZoomFactorProperty, value); } public static readonly BindableProperty MinZoomFactorProperty = BindableProperty.Create(nameof(MinZoomFactor) , typeof(float) , typeof(CameraView) , -1f , BindingMode.OneWayToSource); /// /// Returns minimum zoom factor for current camera. /// public float MinZoomFactor { get => (float)GetValue(MinZoomFactorProperty); set => SetValue(MinZoomFactorProperty, value); } public static readonly BindableProperty MaxZoomFactorProperty = BindableProperty.Create(nameof(MaxZoomFactor) , typeof(float) , typeof(CameraView) , -1f , BindingMode.OneWayToSource); /// /// Returns maximum zoom factor for current camera. /// public float MaxZoomFactor { get => (float)GetValue(MaxZoomFactorProperty); set => SetValue(MaxZoomFactorProperty, value); } public static readonly BindableProperty DeviceSwitchZoomFactorProperty = BindableProperty.Create(nameof(DeviceSwitchZoomFactor) , typeof(float[]) , typeof(CameraView) , Array.Empty() , BindingMode.OneWayToSource); /// /// Returns zoom factors that switch between camera lenses (iOS only). /// public float[] DeviceSwitchZoomFactor { get => (float[])GetValue(DeviceSwitchZoomFactorProperty); set => SetValue(DeviceSwitchZoomFactorProperty, value); } ``` -------------------------------- ### iOS/macOS - NSCameraUsageDescription Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/configuration.md Required iOS/macOS usage description in Info.plist's dict node. Runtime permission is requested with Methods.AskForRequiredPermissionAsync(), which returns true only when camera permission is granted. ```xml NSCameraUsageDescription Enable camera for barcode scanning. ``` -------------------------------- ### AsBarcodeResult (Windows) Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/extensions.md Converts a zxing-cpp `Barcode` result into a `BarcodeResult`. This is a public extension method on `ZXingCpp.Barcode`. ```APIDOC ## AsBarcodeResult (Windows) ### Description Converts a zxing-cpp `Barcode` result into a `BarcodeResult`. This is a public extension method on `ZXingCpp.Barcode`. ### Signature `public static BarcodeResult AsBarcodeResult(this Barcode barcode, Size? imageSize = null, Size? previewSize = null)` ### Parameters - **barcode** (`Barcode`) - Required - A zxing-cpp result (`ZXingCpp.Barcode`). - **imageSize** (`Size?`) - Optional - Analyzed frame size (pixels). - **previewSize** (`Size?`) - Optional - Preview element size. ### Returns `BarcodeResult` - see barcode-result.md. ### Behavior Computes the axis-aligned bounding box of the four corner points (`Position.TopLeft/BottomLeft/TopRight/BottomRight`), then transforms it to preview coordinates when both sizes are provided (uniform scale `max(scaleX, scaleY)` + centering offsets). `BarcodeType` is always `Unknown`; `RawValue` and `DisplayValue` both equal `Barcode.Text`; format comes from `ConvertFromZxingFormats`. ``` -------------------------------- ### ZXingCpp.Barcode.AsBarcodeResult extension Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/extensions.md Converts a zxing-cpp Barcode result to BarcodeResult on Windows. Computes the axis-aligned bounding box from the four corner points and transforms to preview coordinates when both sizes are provided (uniform scale max(scaleX, scaleY) plus centering offsets). BarcodeType is always Unknown; RawValue and DisplayValue equal Barcode.Text. ```csharp public static BarcodeResult AsBarcodeResult(this Barcode barcode, Size? imageSize = null, Size? previewSize = null) ``` -------------------------------- ### CameraViewHandler class declaration Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view-handler.md Partial declaration of the handler that connects CameraView to the native BarcodeView. It holds a single CameraManager field; the platform partial implements CreatePlatformView(). ```csharp public partial class CameraViewHandler : ViewHandler { private CameraManager? _cameraManager; ... } ``` -------------------------------- ### CameraViewHandler CameraViewMapper property map Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view-handler.md Property mapper that forwards CameraView property changes to the corresponding CameraManager update method. The BackgroundColor entry overrides MAUI's base handler entry. Properties like ForceInverted and PoolingInterval are not mapped; they are read per frame by analyzers or written back by the platform. ```csharp public static readonly PropertyMapper CameraViewMapper = new() { [nameof(CameraView.CameraFacing)] = (handler, virtualView) => handler?._cameraManager?.UpdateCamera(), [nameof(CameraView.CaptureQuality)] = (handler, virtualView) => handler?._cameraManager?.UpdateResolution(), [nameof(CameraView.BarcodeSymbologies)] = (handler, virtualView) => handler?._cameraManager?.UpdateSymbologies(), [nameof(CameraView.TorchOn)] = (handler, virtualView) => handler?._cameraManager?.UpdateTorch(), [nameof(CameraView.BackgroundColor)] = (handler, virtualView) => handler?._cameraManager?.UpdateBackgroundColor(), [nameof(CameraView.CameraEnabled)] = (handler, virtualView) => handler?._cameraManager?.UpdateCameraEnabled(), [nameof(CameraView.AimMode)] = (handler, virtualView) => handler?._cameraManager?.UpdateAimMode(), [nameof(CameraView.TapToFocusEnabled)] = (handler, virtualView) => handler?._cameraManager?.UpdateTapToFocus(), [nameof(CameraView.RequestZoomFactor)] = (handler, virtualView) => handler?._cameraManager?.UpdateZoomFactor(), [nameof(CameraView.VibrationOnDetected)] = (handler, virtualView) => handler?._cameraManager?.UpdateVibration() }; ``` -------------------------------- ### ScanFromImageAsync(FileResult) Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Scans an image file for barcodes and returns the detected results. ```APIDOC ## ScanFromImageAsync(FileResult) ### Description Scans a picked image file for barcodes and returns the detected results. ### Method ScanFromImageAsync ### Parameters - **file** (FileResult) - Required - The image file to scan. ### Returns IReadOnlySet - A set of barcode results, each containing BarcodeFormat and DisplayValue. ### Example ```csharp var file = await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Pick an image with a barcode" }); if (file is not null) { IReadOnlySet results = await Methods.ScanFromImageAsync(file); foreach (var result in results) { Console.WriteLine($"{result.BarcodeFormat}: {result.DisplayValue}"); } } ``` ``` -------------------------------- ### Handle OnDetected event and print BarcodeResult properties Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/barcode-result.md Handles the OnDetected event, iterating through each BarcodeResult to print its properties to the console. Use this to access barcode data after detection. ```csharp private void OnDetected(object sender, OnDetectionFinishedEventArg e) { foreach (BarcodeResult result in e.BarcodeResults) { Console.WriteLine($"Format: {result.BarcodeFormat}"); Console.WriteLine($"Display: {result.DisplayValue}"); Console.WriteLine($"Raw: {result.RawValue}"); Console.WriteLine($"Bytes: {Convert.ToHexString(result.RawBytes)}"); Console.WriteLine($"Preview box: {result.PreviewBoundingBox}"); Console.WriteLine($"Image box: {result.ImageBoundingBox}"); Console.WriteLine($"Type: {result.BarcodeType}"); } } ``` -------------------------------- ### ScanFromImageAsync overloads signatures Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Four overloads of ScanFromImageAsync, each accepting a different input type: imageArray (encoded bytes), file (MAUI FileResult), url (remote URL), or stream (open image stream). Each returns a deduplicated HashSet via BarcodeResult.Equals; the set may be empty. On plain net10.0, every overload throws PlatformNotSupportedException. ```csharp public static async Task> ScanFromImageAsync(byte[] imageArray) public static async Task> ScanFromImageAsync(FileResult file) public static async Task> ScanFromImageAsync(string url) public static async Task> ScanFromImageAsync(Stream stream) ``` -------------------------------- ### AskForRequiredPermissionAsync Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Static method that checks and requests camera permission, returning whether it is granted. ```APIDOC ## AskForRequiredPermissionAsync ### Description Requests camera permission if not already granted and returns whether permission is available. ### Method N/A (static method) ### Endpoint `Methods.AskForRequiredPermissionAsync()` ### Parameters No parameters. ### Request Example ```csharp bool granted = await Methods.AskForRequiredPermissionAsync(); ``` ### Response #### Success Response - **Returns** `Task` — `true` if camera permission is granted (either already or after request); `false` otherwise. #### Response Example ```csharp bool granted = await Methods.AskForRequiredPermissionAsync(); ``` ``` -------------------------------- ### CaptureQuality bindable property Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Bindable property for setting the capture quality of the image analysis feed. Default and recommended value is CaptureQuality.Medium. Higher values give more precision, lower values give faster scanning. The exact per-platform resolution mapping (854×480 to 3840×2160, 720p default) is described in types.md. ```csharp public static readonly BindableProperty CaptureQualityProperty = BindableProperty.Create(nameof(CaptureQuality) , typeof(CaptureQuality) , typeof(CameraView) , CaptureQuality.Medium , BindingMode.TwoWay , propertyChanged: (bindable, value, newValue) => ((CameraView)bindable).CaptureQuality = (CaptureQuality)newValue); /// /// Set the capture quality for the image analysis. /// Recommended and default value is Medium. /// Use highest values for more precision or lower for fast scanning. /// public CaptureQuality CaptureQuality { get => (CaptureQuality)GetValue(CaptureQualityProperty); set => SetValue(CaptureQualityProperty, value); } ``` -------------------------------- ### ScanFromImageAsync(byte[]) Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Scans raw image bytes for barcodes and returns the detected results. Behavior differs across platforms for undecodable images. ```APIDOC ## ScanFromImageAsync(byte[]) ### Description Scans raw image bytes for barcodes and returns the detected results. On Android/iOS, an undecodable image yields an empty set; on Windows, decode failures throw an exception. ### Method ScanFromImageAsync ### Parameters - **imageBytes** (byte[]) - Required - The raw image bytes to scan. ### Returns IReadOnlySet - A set of barcode results, each containing BarcodeFormat, DisplayValue, and RawValue. ### Exceptions - **Exception** - Thrown on decode failures on Windows and bad URLs. ### Example ```csharp byte[] imageBytes = await LoadImageBytesAsync(); try { var results = await Methods.ScanFromImageAsync(imageBytes); if (results.Count == 0) { // No barcode found (or image could not be decoded on Android/iOS — // an undecodable image yields an empty set there). return; } var qr = results.First(r => r.BarcodeFormat.HasFlag(BarcodeFormats.QRCode)); await Launcher.OpenAsync(qr.RawValue); } catch (Exception ex) // decode failures on Windows and bad URLs { await DisplayAlertAsync("Scan failed", ex.Message, "OK"); } ``` ``` -------------------------------- ### ScanFromImageAsync(FileResult file) Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/methods.md Scans barcodes from an image file selected via the MAUI file picker. ```APIDOC ## ScanFromImageAsync(FileResult file) ### Description Scans barcodes from an image file picked via the MAUI file picker. Returns a deduplicated set of results. ### Method N/A (static method) ### Endpoint `Methods.ScanFromImageAsync(FileResult file)` ### Parameters #### Path Parameters - **file** (`FileResult`) - Required - File picked via MAUI file picker; decoded from its stream. ### Request Example ```csharp FileResult file = await FilePicker.Default.PickAsync(); IReadOnlySet results = await Methods.ScanFromImageAsync(file); ``` ### Response #### Success Response - **Returns** `Task>` — a set of `BarcodeResult` objects (may be empty). #### Response Example ```csharp IReadOnlySet results = await Methods.ScanFromImageAsync(file); ``` ``` -------------------------------- ### BarcodeResult equality and hash code implementation Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/barcode-result.md Implements value equality for BarcodeResult. Two results are equal when their payload text (RawValue, falling back to DisplayValue) matches and their ImageBoundingBox rectangles intersect. GetHashCode is based on payload text only, and Equals(object?) returns false for non-BarcodeResult arguments. ```csharp public bool Equals(BarcodeResult? other) { if (other is null) return false; var value = !string.IsNullOrEmpty(RawValue) ? RawValue : DisplayValue; var otherValue = !string.IsNullOrEmpty(other.RawValue) ? other.RawValue : other.DisplayValue; return value == otherValue && ImageBoundingBox.IntersectsWith(other.ImageBoundingBox); } public override bool Equals(object? obj) { if (obj is BarcodeResult barcode) return Equals(barcode); else return false; } public override int GetHashCode() { var value = !string.IsNullOrEmpty(RawValue) ? RawValue : DisplayValue; return value.GetHashCode(); } ``` -------------------------------- ### CameraView class declaration Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/camera-view.md Declares the CameraView class as a partial class deriving from View in the BarcodeScanning namespace. This is the primary public component for camera preview and scanning. ```csharp namespace BarcodeScanning; public partial class CameraView : View ``` -------------------------------- ### Invoke OnImageCaptured with event args Source: https://github.com/afriscic/barcodescanning.native.maui/blob/master/_autodocs/api-reference/event-args.md Shows how the OnImageCaptured event is raised with the OnImageCapturedEventArg payload. This occurs inside CameraView.TriggerOnDetectionFinished when a frame was captured (CaptureNextFrame with at least one result, or ForceFrameCapture). ```csharp OnImageCaptured?.Invoke(this, new OnImageCapturedEventArg { Image = image }); ```