Skip to content

4. Usage of Maui

Jimmy Pun edited this page Feb 22, 2023 · 3 revisions

- Set support barcode format

Call it before you start to init CameraView, default is All

BarcodeScanner.Mobile.Methods.SetSupportBarcodeFormat(BarcodeFormats.Code39 | BarcodeFormats.QRCode | BarcodeFormats.Code128);

- XAML setup

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SampleApp.Maui.Page1"
             xmlns:gv="clr-namespace:BarcodeScanner.Mobile;assembly=BarcodeScanner.Mobile.Maui"
             Title="Page1">
   <ContentPage.Content>
     <ScrollView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
	 <!--VirbationOnDetected: Indicate the device will vibrate or not when detected barcode, default is True
		 TorchOn: Indicate the torch will on or not when the view appear, default is False
		 IsScanning : Indicate whether the device will start scanning after it is opened, default is True
		 RequestedFPS: Affect Android only, remove it if you want a default value (https://developers.google.com/android/reference/com/google/android/gms/vision/CameraSource.Builder.html#public-camerasource.builder-setrequestedfps-float-fps)
		 ScanInterval: Scan interval for iOS, default is 500ms and the minimum is 100ms, please be reminded that double scanning may be occurred if it is too small
		 -->
          <gv:CameraView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" OnDetected="CameraView_OnDetected" Grid.Row="1"
                           TorchOn="False" VibrationOnDetected="False" ScanInterval="50" x:Name="Camera"/>

     </ScrollView>
   </ContentPage.Content>
</ContentPage>

- Handle result in callback

Once barcode detected, "OnDetected" event will be triggered, do the stuff you want with the barcode, it will contains type and display value

   private async void CameraView_OnDetected(object sender, OnDetectedEventArg e)
        {
            List<BarcodeResult> obj = e.BarcodeResults;

            string result = string.Empty;
            for (int i = 0; i < obj.Count; i++)
            {
                result += $"Type : {obj[i].BarcodeType}, Value : {obj[i].DisplayValue}{Environment.NewLine}";
            }
            this.Dispatcher.Dispatch(async () =>
            {
                // DisplayAlert is not working on iOS, this is an known issue on Maui, but the barcode scanner is able to scan the barcode and return results
                // https://github.com/dotnet/maui/issues/7444
                await DisplayAlert("Result", result, "OK");
		// If you want to start scanning again
                Camera.IsScanning = true;
            });
            
        }

- Ask for permission

bool allowed = await BarcodeScanner.Mobile.Methods.AskForRequiredPermission();

- Handle Torch

   // CameraView is from the Name of gv:CameraView defined in XAML
   CameraView.TorchOn = true / false;

- Restart scanning

// CameraView is from the Name of gv:CameraView defined in XAML
CameraView.IsScanning = true / false;

- Use front/back camera

// CameraView is from the Name of gv:CameraView defined in XAML
// Default is CameraFacing.Back
CameraView.CameraFacing = CameraFacing.Back / CameraFacing.Front;

- Modify caputre quality

This property is to balance speed/precision

// CameraView is from the Name of gv:CameraView defined in XAML
// Default is CaptureQuality.Medium
CameraView.CaptureQuality = CaptureQuality.Lowest / CaptureQuality.Low / CaptureQuality.Medium / CaptureQuality.High / CaptureQuality.Highest;

- Mvvm support

Properties support MVVM:

  • OnDetectedCommand
  • IsScanning
  • TorchOn
  • VibrationOnDetected
  • ScanInterval
  • CameraFacing
  • CaptureQuality

Check out the MVVM from sample app for demo

<gv:CameraView Grid.Row="1" Grid.Column="1"
               OnDetectedCommand="{Binding OnDetectCommand}" 
               IsScanning="{Binding IsScanning}" 
               TorchOn="{Binding TorchOn}" VibrationOnDetected="{Binding VibrationOnDetected}" ScanInterval="{Binding ScanInterval}"
               x:Name="Camera" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>

- Scan from Image

  1. Get the image byte array by your method.
//Used MediaPlugin in sample for example
 var file = await CrossMedia.Current.PickPhotoAsync();
Stream stream = file.GetStream();
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
  1. Analyze the image and wait for result
List<BarcodeResult> obj = await BarcodeScanner.Mobile.Methods.ScanFromImage(bytes);