728x90
728x170

MAUI 에서 Google Vision 사용하는 방법입니다.

1. 'BarcodeScanner.Mobile.Maui' Nuget Package 설치 (시험판 포함 체크 필요)


2. BarcodeScannerHandler등록

MauiProgram.cs

using BarcodeScanner.Mobile;

using Microsoft.Extensions.Logging;

namespace Maui.VisionTest;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            })
            .ConfigureMauiHandlers(handlers =>
            {
                // Add the handlers
                handlers.AddBarcodeScannerHandler();
            });

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }
}

 

3. 화면에 CameraView 와 결과 표시 항목(Label) 추가

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="Maui.VisionTest.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:gv="clr-namespace:BarcodeScanner.Mobile;assembly=BarcodeScanner.Mobile.Maui">

    <Grid BackgroundColor="Black" RowDefinitions="7*,3*">

        <gv:CameraView
            x:Name="Camera"
            Margin="10"
            HorizontalOptions="FillAndExpand"
            OnDetected="Camera_OnDetected"
            ScanInterval="100"
            TorchOn="False"
            VerticalOptions="FillAndExpand"
            VibrationOnDetected="False" />

        <Button
            x:Name="facingButton"
            Margin="0,0,0,15"
            BackgroundColor="White"
            Clicked="FacingButton_Clicked"
            HeightRequest="40"
            HorizontalOptions="End"
            Text="Front/Rear"
            TextColor="Black"
            VerticalOptions="End"
            WidthRequest="110" />

        <ScrollView Grid.Row="1">
            <Grid>
                <Button
                    x:Name="clearButton"
                    Margin="5,0"
                    BackgroundColor="White"
                    Clicked="ClearButton_Clicked"
                    HeightRequest="40"
                    HorizontalOptions="End"
                    Text="Clear"
                    TextColor="Black"
                    VerticalOptions="Start"
                    WidthRequest="60" />
                <Label
                    x:Name="resultLabel"
                    Text=""
                    TextColor="White" />
            </Grid>
        </ScrollView>
    </Grid>

</ContentPage>

 

4. 버튼 이벤트 구현 및 바코드 인식 결과 도출시 화면에 표시 처리

MainPage.xaml.cs

using BarcodeScanner.Mobile;

namespace Maui.VisionTest;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        // 권한 획득
        BarcodeScanner.Mobile.Methods.AskForRequiredPermission();
    }

    private void Camera_OnDetected(object sender, BarcodeScanner.Mobile.OnDetectedEventArg e)
    {
        List<BarcodeResult> barcodeResults = e.BarcodeResults;

        string result = string.Empty;
        for (int i = 0; i < barcodeResults.Count; i++)
        {
            result += $"BarcodeType : {barcodeResults[i].BarcodeType}, Result : {barcodeResults[i].DisplayValue}{Environment.NewLine}";
        }

        Dispatcher.Dispatch(() =>
        {
            // 중복 결과 방지
            if (!resultLabel.Text.Contains(result))
            {
                // 결과 표시
                resultLabel.Text = result + Environment.NewLine + resultLabel.Text;
            }

            // 스캐딩 다시 시작
            Camera.IsScanning = true;
        });
    }

    private void FacingButton_Clicked(object sender, EventArgs e)
    {
        if (this.Camera.CameraFacing == CameraFacing.Front)
        {
            this.Camera.CameraFacing = CameraFacing.Back;
        }
        else
        {
            this.Camera.CameraFacing = CameraFacing.Front;
        }
    }

    private void ClearButton_Clicked(object sender, EventArgs e)
    {
        this.resultLabel.Text = "";
    }
}

e.BarcodeResults 에 바코드 인식결과들이 들어있습니다.

동시에 여러게의 바코드를 인식합니다.


결과


소스

https://github.com/kei-soft/Maui.VisionTest

 

GitHub - kei-soft/Maui.VisionTest: Maui Google Vision Sample

Maui Google Vision Sample. Contribute to kei-soft/Maui.VisionTest development by creating an account on GitHub.

github.com

 

iOS 에서는 아래와 같은 에러가 발생됩니다.

심각도 코드 설명 프로젝트 파일 줄 비표시 오류(Suppression) 상태
오류 MSB4018 "ResolveNativeReferences" 작업에서 예기치 않은 오류가 발생했습니다.
System.AggregateException: 하나 이상의 오류가 발생했습니다. ---> System.ComponentModel.Win32Exception: 지정된 파일을 찾을 수 없습니다

해결방법은 알게되면 포스팅을 수정하겠습니다. 혹시 방법을 아신다면 댓글 환영합니다.^^

728x90
그리드형
Posted by kjun
,