跳過到頁腳內容
使用 IRONQR

如何使用 .NET MAUI 進行 QR 碼掃描器

隨著行動應用利用二維碼快速獲取資訊的興起,對高效易整合的二維碼掃描器以及用於掃描條碼的.NET MAUI 條碼掃描器的需求日益增長。 .NET MAUI(多平台應用程式使用者介面)是微軟的跨平台框架,為建構跨 iOS、Android、macOS 和 Windows 平台的應用程式提供了一個統一的環境。 在 .NET MAUI 應用程式中掃描二維碼時,開發人員需要一個直覺且功能強大的程式庫來管理流程。

IronQR是一個受歡迎的庫,它允許開發人員快速、準確、可靠地產生和解碼二維碼。 本文將引導您完成將 IronQR 與 .NET MAUI 集成,以建立一個可以在多個平台上無縫工作的二維碼/條碼掃描器。

如何使用 IronQR 實現二維碼掃描

  1. 建立一個 .NET MAUI 專案。
  2. 安裝 IronQR NuGet 套件。
  3. 設定相機和檔案儲存權限。
  4. 實作二維碼掃描器。

IronQR for .NET MAUI 行動應用程式簡介

IronQR 是一個功能強大、易於使用的函式庫,可簡化 .NET 應用程式(包括 .NET MAUI 行動應用程式)中二維碼的產生和解碼,實現二維碼和條碼掃描功能。 它為跨平台(如 iOS、Android、macOS 和 Windows)整合二維碼和條碼掃描功能提供了快速可靠的解決方案,這對於建立跨平台行動應用程式至關重要。

IronQR for .NET MAUI 行動應用的功能

-跨平台支援:可在 MAUI 應用程式中無縫運行於 iOS、Android、macOS 和 Windows 平台。 -二維碼掃描:高效率解碼各種類型的二維碼(網址、文字、聯絡資訊等)。 它還支援使用高效的條碼檢測演算法讀取多個條碼。 -二維碼產生:此功能可以輕鬆地從 URL、文字等資料產生二維碼。 -相機權限處理:自動處理相機權限要求,簡化掃描流程。 -高效能:快速可靠地掃描和產生二維碼,資源佔用極低。 -可自訂設定:提供掃描參數和二維碼外觀的自訂選項。 -輕鬆整合:只需簡單的 API 和最少的設置,即可將二維碼掃描和生成功能添加到您的 .NET MAUI 應用程式中。 -錯誤處理:提供詳細的錯誤訊息和故障排除,確保在各種情況下都能流暢運作。 -無外部相依性:IronQR 獨立運行,減少了對第三方程式庫或複雜配置的需求,這與 ZXing 條碼掃描器不同。 -多格式支援:支援多種二維碼格式,確保與現實世界中使用的各種二維碼相容。

先決條件

在開始實施之前,請確保您已具備以下先決條件:

  1. 已安裝Visual Studio 2022 或更高版本
  2. .NET 6.0 SDK 或更高版本(因為 .NET MAUI 是基於 .NET 6 及更高版本構建的)。
  3. IronQR NuGet 包,用於二維碼掃描和條碼檢測。
  4. .NET MAUI 應用程式(如果您還沒有 MAUI 應用程序,可以在 Visual Studio 中建立一個新的 MAUI 應用程式)。

步驟 1:建立一個 .NET MAUI 項目

首先,我們建立一個簡單的.NET MAUI專案:

  1. 開啟 Visual Studio,然後按一下"建立新專案"
  2. 選擇.NET MAUI 應用程式範本。

    新專案

  3. 為項目命名(例如,MauiQRCodeScanner),選擇一個位置,然後按一下"下一步"

    專案配置

    選擇所需的 .NET 版本,然後按一下"建立"。

    目標框架

步驟 2:安裝 IronQR NuGet 套件

IronQR 是一個提供二維碼產生和掃描功能的第三方函式庫。 要安裝 IronQR,您需要透過 NuGet 添加它:

  1. 在 Visual Studio 中,以滑鼠右鍵按一下解決方案資源管理器中的"依賴項"
  2. 按一下"管理 NuGet 套件"
  3. "瀏覽"標籤中,搜尋 IronQR,然後按一下相關軟體包上的"安裝" (通常是 IronQR 或 IronQR.Maui,如果專門用於 MAUI)。
  4. 接受所有許可協議,並確保庫已安裝。

    IronQR

步驟 3:設定相機和檔案儲存權限

要讓您的應用程式能夠掃描二維碼,您需要在行動平台(iOS 和 Android)上請求相機權限。 以下是如何新增以下權限的方法。

安卓

AndroidManifest.xml檔案中新增相機權限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
XML

iOS

Info.plist檔案中新增相機使用說明:

<key>NSCameraUsageDescription</key>
<string>We need access to your camera to scan QR codes</string>
<key>NSCameraUsageDescription</key>
<string>We need access to your camera to scan QR codes</string>
XML

第四步:實現二維碼掃描器

現在,讓我們在 MAUI 條碼掃描器應用程式中為二維碼掃描器建立一個簡單的使用者介面。我們將使用按鈕來觸發掃描過程,並使用標籤來顯示掃描到的二維碼文字。

編輯 XML 命名空間中的MainPage.xaml檔案。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="MauiQRCodeScanner.MainPage">

    <StackLayout Padding="20" VerticalOptions="Center">
        <Button x:Name="scanButton" Text="Scan QR Code" Clicked="OnScanButtonClicked" />
        <Label x:Name="resultLabel" Text="Scan Result will appear here" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
    </StackLayout>
</ContentPage>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="MauiQRCodeScanner.MainPage">

    <StackLayout Padding="20" VerticalOptions="Center">
        <Button x:Name="scanButton" Text="Scan QR Code" Clicked="OnScanButtonClicked" />
        <Label x:Name="resultLabel" Text="Scan Result will appear here" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
    </StackLayout>
</ContentPage>
XML

現在,在MainPage.xaml.cs中,您將處理相機權限和二維碼掃描邏輯。 以下是具體實作方法:

using IronQrCode;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Essentials;

namespace MauiQRCodeScanner
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            License.LicenseKey = "Your key";  // Add your IronQR license key here
            InitializeComponent();
        }

        // OnScanButtonClicked method with object sender as input
        private async void OnScanButtonClicked(object sender, EventArgs e)
        {
            // Check for camera permission
            var status = await Permissions.RequestAsync<Permissions.Camera>();
            if (status != PermissionStatus.Granted)
            {
                await DisplayAlert("Permission Denied", "Cannot scan QR codes without camera permission", "OK");
                return;
            }

            // Start scanning QR codes
            try
            {
                var images = await FilePicker.Default.PickAsync(new PickOptions
                {
                    PickerTitle = "Pick image",
                    FileTypes = FilePickerFileType.Images
                });
                var imageSource = images.FullPath.ToString();

                var inputBmp = AnyBitmap.FromFile(imageSource);
                // Load the asset into QrImageInput
                QrImageInput imageInput = new QrImageInput(inputBmp);

                // Create a QR Reader object
                QrReader reader = new QrReader();

                // Read the input and get all embedded QR Codes
                IEnumerable<QrResult> results = reader.Read(imageInput);

                if (results.Any())
                {
                    resultLabel.Text = "Scanned Text: " + results.First().Value; 
        // Display the result
                }
                else
                {
                    resultLabel.Text = "No QR code detected";
                }
        }
        catch (Exception ex)
        {
            resultLabel.Text = "Error: " + ex.Message;
        }
        }
    }
}
using IronQrCode;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Essentials;

namespace MauiQRCodeScanner
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            License.LicenseKey = "Your key";  // Add your IronQR license key here
            InitializeComponent();
        }

        // OnScanButtonClicked method with object sender as input
        private async void OnScanButtonClicked(object sender, EventArgs e)
        {
            // Check for camera permission
            var status = await Permissions.RequestAsync<Permissions.Camera>();
            if (status != PermissionStatus.Granted)
            {
                await DisplayAlert("Permission Denied", "Cannot scan QR codes without camera permission", "OK");
                return;
            }

            // Start scanning QR codes
            try
            {
                var images = await FilePicker.Default.PickAsync(new PickOptions
                {
                    PickerTitle = "Pick image",
                    FileTypes = FilePickerFileType.Images
                });
                var imageSource = images.FullPath.ToString();

                var inputBmp = AnyBitmap.FromFile(imageSource);
                // Load the asset into QrImageInput
                QrImageInput imageInput = new QrImageInput(inputBmp);

                // Create a QR Reader object
                QrReader reader = new QrReader();

                // Read the input and get all embedded QR Codes
                IEnumerable<QrResult> results = reader.Read(imageInput);

                if (results.Any())
                {
                    resultLabel.Text = "Scanned Text: " + results.First().Value; 
        // Display the result
                }
                else
                {
                    resultLabel.Text = "No QR code detected";
                }
        }
        catch (Exception ex)
        {
            resultLabel.Text = "Error: " + ex.Message;
        }
        }
    }
}
Imports IronQrCode
Imports Microsoft.Maui.Controls
Imports Microsoft.Maui.Essentials

Namespace MauiQRCodeScanner
	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			License.LicenseKey = "Your key" ' Add your IronQR license key here
			InitializeComponent()
		End Sub

		' OnScanButtonClicked method with object sender as input
		Private Async Sub OnScanButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
			' Check for camera permission
			Dim status = Await Permissions.RequestAsync(Of Permissions.Camera)()
			If status <> PermissionStatus.Granted Then
				Await DisplayAlert("Permission Denied", "Cannot scan QR codes without camera permission", "OK")
				Return
			End If

			' Start scanning QR codes
			Try
				Dim images = Await FilePicker.Default.PickAsync(New PickOptions With {
					.PickerTitle = "Pick image",
					.FileTypes = FilePickerFileType.Images
				})
				Dim imageSource = images.FullPath.ToString()

				Dim inputBmp = AnyBitmap.FromFile(imageSource)
				' Load the asset into QrImageInput
				Dim imageInput As New QrImageInput(inputBmp)

				' Create a QR Reader object
				Dim reader As New QrReader()

				' Read the input and get all embedded QR Codes
				Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

				If results.Any() Then
					resultLabel.Text = "Scanned Text: " & results.First().Value
		' Display the result
				Else
					resultLabel.Text = "No QR code detected"
				End If
		Catch ex As Exception
			resultLabel.Text = "Error: " & ex.Message
		End Try
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼解釋

-權限:我們使用Permissions.RequestAsync<Permissions.Camera> ()請求相機權限。 Permissions.RequestAsync<Permissions.Camera> () 。 如果權限被拒絕,則會向使用者顯示警告。

  • IronQR 掃描器:使用 IronQR 庫物件和方法來掃描二維碼。 QrReader.Read()方法嘗試解碼二維碼,並將結果顯示在標籤上。

輸入二維碼

QR 圖碼輸入

輸出

QR 圖碼輸出

選擇所需的二維碼或從相機畫面中捕捉二維碼。

選擇二維碼

結果在使用者介面中顯示如下。

二維碼使用者介面輸出

IronQR 授權(提供試用版)

IronQR 透過行動應用程式程式碼中的許可證金鑰來運作。 開發者可以輕鬆地從許可證頁面取得試用許可證。 在使用 IronQR 庫之前,請將許可證資訊如下新增至程式碼。

License.LicenseKey = "Your License";
License.LicenseKey = "Your License";
License.LicenseKey = "Your License"
$vbLabelText   $csharpLabel

結論

在本文中,我們逐步介紹如何使用 IronQR 在 .NET MAUI 應用程式中建立二維碼掃描器。 我們首先建立了一個 .NET MAUI 應用程序,安裝了 IronQR 包,並實作了 UI 和掃描邏輯。 IronQR 讓 .NET MAUI 應用程式中的二維碼掃描變得極為簡單且有效率。

IronQR 庫的設計目標是跨平台的,確保使用 .NET MAUI 建立的應用程式可以在所有目標裝置上(無論是智慧型手機、平板電腦還是桌上型電腦系統)一致地存取二維碼功能。 IronQR 還支援自動相機權限處理等功能,讓整合式二維碼掃描變得更加容易,無需手動管理權限。

簡而言之,IronQR for .NET MAUI 使開發人員能夠在行動應用程式中快速實現二維碼掃描和生成功能,從而簡化開發並改善所有平台上的使用者體驗。

常見問題解答

如何在 .NET MAUI 應用程式中整合 QR Code 掃描器?

若要在 .NET MAUI 應用程式中整合 QR Code 掃描器,請透過 NuGet 安裝 IronQR 函式庫,並使用 QrReader.Read() 來解碼 QR Code。

為 QR 掃描建立 .NET MAUI 專案的步驟為何?

首先開啟 Visual Studio,使用 .NET MAUI App 模板建立新專案,並選擇必要的 .NET 版本。然後,安裝 IronQR 函式庫來實作 QR 掃描。

在 .NET MAUI 應用程式中,哪些權限對 QR 掃描是必要的?

QR 掃描需要相機權限。在 Android 上,請在 AndroidManifest.xml 中新增必要的權限;在 iOS 上,請更新 Info.plist 中的相機使用說明。

如何在 .NET MAUI 應用程式中管理攝影機權限?

使用 Permissions.RequestAsync<Permissions.Camera>() 來請求攝影機權限。透過顯示警告通知使用者來處理拒絕。

使用 IronQR 函式庫進行 QR 掃描有什麼好處?

IronQR 提供跨平台支援、高效能、可自訂設定、自動處理相機權限,以及多格式支援,使其成為 .NET MAUI 應用程式的理想選擇。

如何排除 .NET MAUI 應用程式中的 QR Code 掃描問題?

確保 IronQR 函式庫已正確安裝、攝影機權限已授予,以及裝置攝影機已正常運作。使用 try-catch 區塊檢查程式碼中是否有任何錯誤。

開始使用 .NET MAUI 和 QR 掃描進行開發需要哪些條件?

您需要 Visual Studio 2022 或更新版本、.NET 6.0 SDK 或更新版本,以及 IronQR NuGet 套件,以方便進行 QR Code 掃描和 BarCode 檢測。

如何取得 QR code library 的試用授權?

請造訪 IronQR 授權頁面,取得試用授權金鑰。在使用 IronQR 功能之前,請將授權金鑰插入您的程式碼中。

IronQR 函式庫支援哪些 QR 掃描格式?

IronQR 支援多種 QR Code 和 BarCode 格式,確保可在不同的應用程式和平台上使用。

如何在 .NET 應用程式中產生 QR 碼?

使用 IronQR 函式庫的方法來有效率地產生 QR 碼,讓您可以根據應用程式的需求自訂設定。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。