Windows 및 Android용 .NET MAUI 바코드 및 QR 코드 리더를 구축하는 방법
개발 환경
비주얼 스튜디오 2022 미리보기
MAUI 템플릿을 받으려면 Visual Studio를 2022 미리 보기로 업그레이드해야 합니다.
.NET MAUI에서 바코드 및 QR 코드 리더를 구축하는 단계
다음 단락에서는 처음부터 .NET MAUI 앱을 만듭니다. 다양한 종속성을 설치하는 방법과 Windows 및 Android용 교차 플랫폼 API를 정의하는 방법을 볼 수 있습니다.
1단계: .NET MAUI 프로젝트 생성
프로젝트 생성 대화 상자에서 검색 상자에
maui를 입력하거나 MAUI에서 All project types를 선택하여 MAUI 템플릿을 빠르게 찾습니다.
기본적으로 템플릿은 Windows, Android, iOS, macOS 및 Tizen용 프로젝트 스켈레톤을 생성합니다. iOS, macOS 및 Tizen의 관련 코드 및 구성을 제거하여 프로젝트를 정리합니다.
2단계: Windows 및 Android에 대해 각각 종속성 설치
Barcode 및 QR Code SDK를 설치하려면 시작
NuGet Package Manager:BarcodeQRCodeSDK Windows용.
Xamarin.Dynamsoft.Barcode.Android 안드로이드용.
종속 패키지는 플랫폼에 따라 다르므로 조건부로 각 플랫폼에 상관되어야 합니다. NuGet 패키지를 자동으로 설치한 후 빌드 오류를 방지하려면
*.csproj 파일에서 다음 항목을 수동으로 편집해야 합니다.<ItemGroup Condition="'$(TargetFramework)' == 'net6.0-android'">
<PackageReference Include="Xamarin.Dynamsoft.Barcode.Android">
    <Version>9.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup Condition="$(TargetFramework.Contains('-windows')) == true ">
    <PackageReference Include="BarcodeQRCodeSDK" Version="1.2.1" />
</ItemGroup>
3단계: 플랫폼 간 API 정의
공식 튜토리얼 - Invoke platform code 에 따르면
BarcodeQRCodeService.cs 폴더에 Services라는 부분 클래스를 정의합니다.namespace BarcodeQRCode.Services
{
    public partial class BarcodeQRCodeService
    {
        public partial void InitSDK(string license);
        public partial string DecodeFile(string filePath);
    }
}
그런 다음 Windows 및 Android 폴더에 각각
BarcodeQRCodeService.cs 파일을 생성하여 API를 구현합니다.
기계적 인조 인간
using BarcodeQRCode.Platforms.Android;
using Com.Dynamsoft.Dbr;
namespace BarcodeQRCode.Services
{
    public partial class BarcodeQRCodeService
    {
        BarcodeReader reader;
        public partial void InitSDK(string license)
        {
            BarcodeReader.InitLicense(license, new DBRLicenseVerificationListener());
            reader = new BarcodeReader();
        }
        public partial string DecodeFile(string filePath)
        {
            string decodingResult = "";
            try
            {
                TextResult[] results = reader.DecodeFile(filePath);
                if (results != null)
                {
                    foreach (TextResult result in results)
                    {
                        decodingResult += result.BarcodeText + "\n";
                    }
                }
                else
                {
                    decodingResult = "No barcode found.";
                }
            }
            catch (Exception e)
            {
                decodingResult = e.Message;
            }
            return decodingResult;
        }
    }
}
윈도우
using Dynamsoft;
namespace BarcodeQRCode.Services
{
    public partial class BarcodeQRCodeService
    {
        BarcodeQRCodeReader? reader = null;
        public partial void InitSDK(string license)
        {
            BarcodeQRCodeReader.InitLicense(license); 
            try
            {
                reader = BarcodeQRCodeReader.Create();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public partial string DecodeFile(string filePath)
        {
            if (reader == null)
                return "";
            string decodingResult = "";            
            try
            {
                string[]? results = reader.DecodeFile(filePath);
                if (results != null)
                {
                    foreach (string result in results)
                    {
                        decodingResult += result + "\n";
                    }
                }
                else
                {
                    decodingResult = "No barcode found.";
                }
            }
            catch (Exception e)
            {
                decodingResult = e.Message;
            }
            return decodingResult;
        }
    }
}
Android의 경우 위의 내용 외에도 인터페이스
DBRLicenseVerificationListener.cs를 구현하기 위해 IDBRLicenseVerificationListener 파일을 만들어야 합니다.using Com.Dynamsoft.Dbr;
namespace BarcodeQRCode.Platforms.Android
{
    public class DBRLicenseVerificationListener : Java.Lang.Object, IDBRLicenseVerificationListener
    {
        public void DBRLicenseVerificationCallback(bool isSuccess, Java.Lang.Exception error)
        {
            if (!isSuccess)
            {
                System.Console.WriteLine(error.Message);
            }
        }
    }
}
4단계: UI 요소 추가
MAUI 템플릿을 사용하여
ReaderPage.xaml라는 새 콘텐츠 페이지를 만듭니다.
이 페이지에는 바코드 및 QR 코드 디코딩 결과를 표시하기 위한 레이블, 이미지 파일을 로드하기 위한 버튼 및 이미지를 표시하기 위한 이미지가 포함되어 있습니다.
<?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="BarcodeQRCode.ReaderPage"
                Title="ReaderPage">
    <ScrollView>
        <VerticalStackLayout>
            <Button 
                Text="Select a file"
                FontAttributes="Bold"
                SemanticProperties.Hint="Decode barcode and QR code from the file"
                Clicked="OnFilePickerClicked"
                HorizontalOptions="Center" />
            <Label 
                FontSize="18"
                FontAttributes="Bold"
                x:Name="ResultLabel"
                HorizontalOptions="Center" />
            <Image
                x:Name="Image"
                SemanticProperties.Description="Decode barcode and QR code from the image file"
                WidthRequest="640"
                HeightRequest="640"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
30-day trial license을 신청한 다음 해당
ReaderPage.xaml.cs 파일로 전환하여 파일 선택 및 이미지 디코딩 논리를 추가합니다.namespace BarcodeQRCode;
using BarcodeQRCode.Services;
public partial class ReaderPage : ContentPage
{
    BarcodeQRCodeService _barcodeQRCodeService;
    public ReaderPage()
    {
        InitializeComponent();
        InitService();
    }
    private async void InitService()
    {
        await Task.Run(() =>
        {
            _barcodeQRCodeService = new BarcodeQRCodeService();
            try
            {
                _barcodeQRCodeService.InitSDK("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==");
            }
            catch (Exception ex)
            {
                DisplayAlert("Error", ex.Message, "OK");
            }
            return Task.CompletedTask;
        });
    }
    private async void OnFilePickerClicked(object sender, EventArgs e)
    {
        FileResult file;
        try
        {
            file = await FilePicker.PickAsync(PickOptions.Images);
            if (file == null) return;
            FileLabel.Text = $"File picked: {file.FileName}";
            Image.Source = ImageSource.FromFile(file.FullPath);
            var result = _barcodeQRCodeService.DecodeFile(file.FullPath);
            ResultLabel.Text = result;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
지금까지
ReaderPage가 완료되었습니다. MainPage.xaml에 버튼을 추가하여 ReaderPage로 이동할 수 있습니다.<Button 
Text="Barcode/QR Code Reader"
FontAttributes="Bold"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnReaderClicked"
HorizontalOptions="Center" />
private void OnReaderClicked(object sender, EventArgs e)
{
    Navigation.PushAsync(new ReaderPage());
}
마지막으로 프레임워크를 선택하고 프로젝트를 빌드합니다.
기계적 인조 인간

윈도우


소스 코드
https://github.com/yushulx/dotnet-maui-barcode-qrcode-reader
Reference
이 문제에 관하여(Windows 및 Android용 .NET MAUI 바코드 및 QR 코드 리더를 구축하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/yushulx/how-to-build-a-net-maui-barcode-and-qr-code-reader-for-windows-and-android-56ba텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)