VintaSoft Barcode .NET SDK 15.0: Руководство для .NET разработчика
В этом разделе
    Генерируйте изображение штрих-кода в MAUI приложении для Android
    В этом разделе
    В этом руководстве показано, как создать пустое MAUI приложение в Visual Studio .NET 2022, сгенерировать изображение штрих-кода и распознать штрих-код в сгенерированном изображении в MAUI приложении для Android.


    Вот шаги, которые необходимо сделать:
    1. Создайте пустое MAUI приложение.

      Откройте Visual Studio .NET 2022 и создайте новый проект типа .NET MAUI приложение:

      Настройте проект для использования .NET 8.0:

    2. Укажите, что MAUI приложение будет использоваться в Android.

      Откройте файл проекта и выберите целевую платформу Android.

    3. Добавьте ссылки на Vintasoft .NET-сборки в MAUI приложение.

      Добавьте ссылки на .NET-сборки Vintasoft.Barcode.dll, Vintasoft.Barcode.SkiaSharp.dll и Vintasoft.Shared.dll из папки "<SdkInstallPath>\VintaSoft Barcode .NET v15.0\Bin\DotNet8\AnyCPU\" в MAUI приложение.
      Комментарий: Ссылка на .NET-сборку Vintasoft.Barcode.SkiaSharp.dll необходима только в том случае, если SDK должен отображать текстовое значение штрих-кода на изображении штрих-кода. Вместо .NET-сборки Vintasoft.Barcode.ImageSharp.dll можно использовать .NET-сборку Vintasoft.Barcode.SkiaSharp.dll.



      Добавьте ссылку на nuget-пакет SkiaSharp в MAUI приложение.

    4. Укажите, что .NET-компилятор не должен минимизировать код .NET-сборок Vintasoft и сборки Mono.Android.

      Откройте файл MAUI проекта и добавьте элементы проекта, которые позволяют указать, что .NET-компилятор не должен минимизировать .NET-сборки Vintasoft и .NET-сборку Mono.Android, если требуется минимизация .NET-сборок MAUI приложения:


      Вот элементы проекта, которые позволяют указать, что .NET-компилятор не должен минимизировать .NET-сборки Vintasoft и .NET-сборку Mono.Android, если требуется минимизация .NET-сборок MAUI приложения:
      <ItemGroup>
              <TrimmerRootAssembly Include="Vintasoft.Barcode" RootMode="library" />
              <TrimmerRootAssembly Include="Vintasoft.Barcode.SkiaSharp" RootMode="library" />
              <TrimmerRootAssembly Include="Vintasoft.Shared" RootMode="library" />
              <TrimmerRootAssembly Include="Mono.Android" RootMode="library" />
      </ItemGroup>
      
      
    5. Добавьте C# код, который регистрирует оценочную версию VintaSoft Barcode .NET SDK.

      Получите C# код для регистрации оценочной версии VintaSoft Barcode .NET SDK в Android как описано в документации, и вставьте полученный код в C# код файла "MainPage.xaml.cs".


      Вот C# код, который регистрирует оценочную версию VintaSoft Barcode .NET SDK:
      // get the application name
      string applicationName = Vintasoft.Barcode.BarcodeGlobalSettings.ApplicationName;
      // if MAUI application is using in Android, Linux or macOS
      if (applicationName.StartsWith("Linux") || applicationName.StartsWith("Android"))
      {
          // register the evaluation license for VintaSoft Barcode .NET SDK
          Vintasoft.Barcode.BarcodeGlobalSettings.Register("LINUX_EVAL_USER", "LINUX_EVAL_USER_EMAIL", "LINUX_EVAL_END_DATE", "LINUX_EVAL_REG_CODE");
      }
      
      
    6. Добавьте C# код, который генерирует изображение штрих-кода и распознает штрих-код в сгенерированном изображении.

      Откройте файл "MainPage.xaml.cs" и добавьте C# код, который создает изображение штрих-кода и распознает штрих-код в созданном изображении, в метод OnCounterClicked.


      Вот C# код, который генерирует изображение штрих-кода и распознает штрих-код в сгенерированном изображении:
      namespace MauiApp1
      {
          public partial class MainPage : ContentPage
          {
              int count = 0;
      
              public MainPage()
              {
                  InitializeComponent();
              }
      
              private void OnCounterClicked(object sender, EventArgs e)
              {
                  // get the application name
                  string applicationName = Vintasoft.Barcode.BarcodeGlobalSettings.ApplicationName;
                  // if MAUI application is using in Android, Linux or macOS
                  if (applicationName.StartsWith("Linux") || applicationName.StartsWith("Android"))
                  {
                      // register the evaluation license for VintaSoft Barcode .NET SDK
                      Vintasoft.Barcode.BarcodeGlobalSettings.Register("LINUX_EVAL_USER", "LINUX_EVAL_USER_EMAIL", "LINUX_EVAL_END_DATE", "LINUX_EVAL_REG_CODE");
                  }
      
                  // create the barcode writer
                  using (Vintasoft.Barcode.BarcodeWriter barcodeWriter = new Vintasoft.Barcode.BarcodeWriter())
                  {
                      // specify that barcode writer must generate DataMatrix barcode
                      barcodeWriter.Settings.Barcode = Vintasoft.Barcode.BarcodeType.DataMatrix;
                      // specify value for DataMatrix barcode
                      barcodeWriter.Settings.Value = "12345";
      
                      // create memory stream that will store generated barcode image as PNG file
                      MemoryStream stream = new MemoryStream();
                      // generate barcode image and save as PNG file to the memory stream
                      barcodeWriter.SaveBarcodeAsImage(stream, "png");
                      stream.Position = 0;
      
                      // create barcode reader
                      using  (Vintasoft.Barcode.BarcodeReader barcodeReader = new Vintasoft.Barcode.BarcodeReader())
                      {
                          // specify that barcode reader must recognize DataMatrix barcodes
                          barcodeReader.Settings.ScanBarcodeTypes = Vintasoft.Barcode.BarcodeType.DataMatrix;
                          // recognize barcodes in PNG file that is stored in memory stream
                          Vintasoft.Barcode.IBarcodeInfo[] barcodeInfos = barcodeReader.ReadBarcodes(stream);
                          // if barcode is not recognized
                          if (barcodeInfos.Length == 0)
                          {
                              DisplayAlert("Barcode Reader", "Barcode is not recognized.", "OK");
                          }
                          // if barcode is recognized
                          else
                          {
                              // display information about recognized DataMatrix barcode
                              DisplayAlert(
                                  "Barcode Reader",
                                  string.Format("Barcode is recognized: Type='{0}', Value='{1}'",
                                      barcodeInfos[0].BarcodeType,
                                      barcodeInfos[0].Value),
                                  "OK");
                          }
                      }
                  }
      
                  count++;
                  if (count == 1)
                      CounterBtn.Text = $"Clicked {count} time";
                  else
                      CounterBtn.Text = $"Clicked {count} times";
      
                  SemanticScreenReader.Announce(CounterBtn.Text);
              }
          }
      
      }
      
      
    7. Подпишите .NET-сборку MAUI приложения, используя файл строгого имени.

      Если у вас есть файл строгого имени, подпишите .NET-сборку MAUI приложения, используя файл строгого имени.


      Если у вас нет файла строгого имени, прочтите, как создать файл строгого имени здесь.
    8. Запустите MAUI приложение в эмуляторе Android и посмотрите результат.