跳過到頁腳內容
使用 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 平台。
  • QR 碼掃描:高效解碼各類 QR 碼(網址、文字、聯絡資訊等)。 它還支援使用高效的條碼檢測演算法讀取多個條碼。
  • QR 碼生成:此功能可輕鬆從 URL、文字等資料生成 QR 碼。
  • 相機權限處理:自動處理相機權限請求,簡化掃描流程。
  • 高效能:以最低的資源消耗,實現快速且可靠的 QR 碼掃描與生成。
  • 可自訂設定:提供掃描參數及 QR 碼外觀的自訂選項。
  • 輕鬆整合:透過簡單的 API 及最低限度的設定,即可為您的 .NET MAUI 應用程式新增 QR 碼掃描與生成功能。
  • 錯誤處理:提供詳細的錯誤訊息與疑難排解指引,確保在各種情境下都能順暢運作。
  • 無外部依賴:IronQR 獨立運作,無需第三方函式庫或複雜設定,這點與 ZXing BarCode 掃描器不同。
  • 多格式支援:支援多種 QR 碼格式,確保與現實世界中廣泛使用的各類 QR 碼相容。

先決條件

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

  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>() 請求相機權限。 如果權限被拒絕,則會向使用者顯示警告。

  • IronQR Scanner:使用 IronQR程式庫的物件與方法來掃描 QR 碼。 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() 來請求相機權限。當被拒絕時,顯示警報以通知用戶。

使用 IronQR 庫進行 QR 掃描的優勢是什麼?

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

如何排查在我的 .NET MAUI 應用中的 QR Code 掃描問題?

確保 IronQR 庫正確安裝,相機權限已授予,並且設備相機正常工作。使用 try-catch 塊檢查代碼中的任何錯誤。

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

您需要 Visual Studio 2022 或更高版本,.NET 6.0 SDK 或更新的版本,以及用於輔助 QR Code 掃描和條碼檢測的 IronQR NuGet 套裝。

如何獲取 QR code 庫的試用許可證?

訪問 IronQR 許可頁面以獲取試用許可證密鑰。在使用 IronQR 功能之前,將許可證密鑰插入您的代碼。

IronQR 庫支持哪些格式的 QR 掃描?

IronQR 支持多種 QR Code 和條碼格式,確保它可以在不同的應用和平台上使用。

如何在 .NET 應用中生成 QR Code?

使用 IronQR 庫的方法高效生成 QR Code,允許您根據應用的需要自定義設置。

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

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我