跳至頁尾內容
USING IRONQR

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

隨著利用QR Code進行快速資訊檢索的行動應用程式的興起,對於能有效且輕鬆整合的QR Code掃描器以及.NET MAUI Barcode掃描器來掃描Barcode的需求正在增長。 .NET MAUI (多平台應用程式UI),是微軟的跨平台框架,提供構建iOS、Android、macOS和Windows應用程式的統一環境。 在.NET MAUI應用程式中掃描QR Code時,開發者需要一個直觀且功能強大的程式庫來管理過程。

IronQR是一個受歡迎的程式庫,允許開發者快速、準確且可靠地生成和解碼QR Code。 本文將引導您整合IronQR和.NET MAUI來構建一個可在多個平台間無縫工作的QR/Barcode掃描器。

如何使用IronQR實現QR Barcode掃描

  1. 建立一個.NET MAUI專案。
  2. 安裝IronQR NuGet套件。
  3. 設置相機和檔案儲存的權限。
  4. 實現QR Code掃描器。

IronQR入門:適用於.NET MAUI行動應用程式

IronQR是一個強大且易於使用的程式庫,簡化了在.NET應用程式中生成和解碼QR Code的過程,包括.NET MAUI行動應用程式中的QR和Barcode掃描功能。 它提供快速且可靠的解決方案,能夠在iOS、Android、macOS和Windows等平台上整合QR Code和Barcode掃描功能,這對於構建跨平台行動應用程式至關重要。

IronQR在.NET MAUI行動應用程式中的特性

  • 支援跨平台:在MAUI應用程式中,能無縫運行於iOS、Android、macOS和Windows平台上。
  • QR Code掃描:有效解碼各類QR Code(網址、文字、聯絡資料等)。 此外,它還支援多種Barcode讀取,並使用高效的Barcode檢測演算法。
  • QR Code生成:允許輕鬆從資料如網址、文字等生成QR Code。
  • 相機權限處理:自動處理相機權限請求,簡化掃描過程。
  • 高效能:快速且可靠的QR Code掃描和生成,並最大程度地降低資源使用。
  • 可自定義設置:提供掃描參數和QR Code外觀的自定義選項。
  • 易於整合:只需簡單的API和最少的設定即可將QR Code掃描和生成新增至您的.NET MAUI應用程式。
  • 錯誤處理:提供詳細的錯誤消息和疑難排解,確保在各種情況下的順暢功能。
  • 無外部依賴:IronQR獨立運行,減少了對第三方程式庫或複雜配置的需求,與ZXing Barcode掃描器不同。
  • 多格式支援:支援多種QR Code格式,確保與實際使用的多種QR Code相容。

先決條件

在進行實施之前,請確保您具備以下先決條件:

  1. 已安裝Visual Studio 2022或更新版本
  2. .NET 6.0 SDK或更新版本(因.NET MAUI是基於.NET 6及其更新版本構建的)。
  3. 用於QR Code掃描和Barcode檢測的IronQR NuGet套件
  4. .NET MAUI應用程式(如果您尚未有一個,您可以在Visual Studio中建立一個新的MAUI應用程式)。

步驟1:建立.NET MAUI專案

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

  1. 打開Visual Studio並點擊建立新專案
  2. 選擇.NET MAUI App範本。

    新專案

  3. 為專案命名(例如,MauiQRCodeScanner),選擇一個位置,然後點擊下一步

    專案配置

    選擇所需的.NET版並點擊建立

    目標框架

步驟2:安裝IronQR NuGet套件

IronQR是一個第三方程式庫,提供QR Code生成和掃描功能。 要安裝IronQR,您需要通過NuGet新增它:

  1. 在Visual Studio中,右鍵點擊方案總管中的依賴項
  2. 點擊管理NuGet套件
  3. 瀏覽選項卡中搜尋IronQR,並點擊相關套件上的安裝(通常是IronQR或特定於MAUI的IronQr.Maui)。
  4. 接受所有許可並確保程式庫已安裝成功。

    IronQR

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

為了讓應用程式掃描QR Code,您需要在行動平台(iOS和Android)上請求相機權限。 以下是您可以新增這些權限的方法。

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

步驟4:實現QR Code掃描器

現在,讓我們在MAUI Barcode掃描器應用程式中建立一個簡單的使用者介面來供QR掃描器使用。我們將使用按鈕來觸發掃描過程,並使用標籤來顯示被掃描的QR Code文字。

在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中,您將處理相機權限和QR Code掃描邏輯。 以下是如何實現的:

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掃描器:使用IronQR程式庫的物件和方法來掃描QR Code。 QrReader.Read()方法嘗試解碼QR Code,結果將顯示在標籤上。

輸入QR Code

QR Code輸入

輸出

QR Code輸出

選擇所需的QR Code或從相機饋影片中捕獲它。

選擇QR Code

結果將顯示在UI中,如下所示。

QR Code UI輸出

IronQR授權(含試用版)

IronQR在行動應用程式程式碼中使用授權金鑰。 開發者可以輕鬆地從授權頁面獲取試用授權。 在使用IronQR程式庫之前,請將授權金鑰放在程式碼中的某個位置,如下所示。

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

結論

在本文中,我們介紹了如何使用IronQR在.NET MAUI應用程式中構建QR Code掃描器的過程。 我們從設置.NET MAUI應用程式開始,安裝了IronQR套件,並實現了UI和掃描邏輯。 IronQR使在.NET MAUI應用程式中掃描QR Code變得極為簡單且有效。

IronQR程式庫設計為跨平台,確保.NET MAUI構建的應用程式能夠在所有目標裝置上一致地存取QR Code功能,無論是智慧型手機、平板電腦或桌上型系統。 IronQR還支援自動處理相機權限等特性,使得整合QR Code掃描變得更輕鬆,而無需手動管理權限。

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

常見問題

我如何在.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掃描和條碼檢測。

我如何獲得QR程式庫的試用授權?

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

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

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

我如何在.NET應用程式中生成QR Codes?

使用IronQR程式庫的方法有效地生成QR Codes,允許您根據應用程式的需求自定義設定。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

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