フッターコンテンツにスキップ
IRONBARCODEの使用

.NET MAUIでQRコードを生成する方法

この記事では、クロスプラットフォームアプリケーションを構築するための現代的なフレームワークである.NET MAUIを使用してQRコードジェネレーターを作成する方法を探ります。 私たちはIronBarcodeライブラリを活用してQRコードを生成し、それを画面に表示します。

.NET MAUIとは?

.NET MAUI(マルチプラットフォーム アプリ UI)は、Xamarin Formsフレームワークの進化版で、単一のコードベースを使用して複数のプラットフォーム向けにネイティブユーザーインターフェイスを構築することを可能にします。 .NET MAUIを使用すると、Android、iOS、macOS、Windows、その他のアプリを作成でき、開発時間と労力を削減できます。

class="hsg-featured-snippet">

.NET MauiでのQRコード生成方法

  1. QRコード生成のためのC#ライブラリをダウンロード
  2. Mauiのユーザーインターフェースを設定する
  3. CreateQrCodeメソッドを使用して文字列からQRコードを生成する
  4. ToJpegBinaryDataメソッドを使用して画像のバイナリデータにアクセスする
  5. バイナリデータをMauiアプリに渡してQRコードを表示する

IronBarcodeの紹介

IronBarcodeは.NETアプリケーション向けの強力なバーコードおよびQRコード生成ライブラリです。 それは、サイズ、エラー修正、エンコーディングオプションなどのカスタマイズ可能な設定を使用して、QRコードを含むさまざまなタイプのバーコードを作成するための使いやすいAPIを提供します。

.NET MAUIプロジェクトのセットアップ

始めるには、Microsoft Visual Studio 2022で新しい.NET MAUIプロジェクトを作成する必要があります。Microsoft Visual Studio Codeを使用することもできますが、手順は異なります。 しかし、Visual Studioを使用することが推奨されます。 以下の手順に従ってプロジェクトを作成してください。

Visual Studio 2022を開きます。以下に示すような画面が表示されます。

.NET MAUIでQRコードを生成する方法: 図1 - Visual Studio 2022 IDE

新しいプロジェクトを作成し、以下に示すようにMAUIテンプレートを検索します。

.NET MAUIでQRコードを生成する方法: 図2

.NET MAUIアプリテンプレートを選択し、次へボタンをクリックします。 次のウィンドウが表示されます。

.NET MAUIでQRコードを生成する方法: 図3

プロジェクトに名前を付け、場所を選択して次へボタンをクリックします。以下に示すようなウィンドウが表示されます。

.NET MAUIでQRコードを生成する方法: 図4

.NET Frameworkを選択します。 私は.NET 7を選択しましたが、.NET 6.0を選択することもできます。プロジェクトは以下に示すように作成されます。

.NET MAUIでQRコードを生成する方法: 図5

このチュートリアルは、主に.NET MAUIアプリケーションをローカルのWindowsマシンに初めてデプロイすることに焦点を当てています。同じコードベースで、必要に応じてAndroidまたはiOSシミュレータ上で構成することができます。

ローカルのWindowsマシンに.NET MAUIアプリケーションをデプロイするには、Visual Studioを使用してこれらの手順に従うことができます:

  1. デバッグターゲットが「Windows Machine」に設定されていることを確認してください。設定されていない場合は、ツールバーのドロップダウンから「Windows Machine」を選択してください。
  2. 「デバッグ開始」ボタンをクリックするか、F5キーを押して、Windowsマシン上でアプリケーションをビルドして実行します。

.NET MAUIでQRコードを生成する方法: 図6

開発者モードがWindowsマシンで有効になっていない場合、Visual Studioは有効にするよう促します。 これを行うには、次の手順に従ってください:

  1. Visual Studioが表示する「Windowsの開発者モードを有効にする」ダイアログボックスで、「開発者の設定」ラベルのリンクを見つけます。

.NET MAUIでQRコードを生成する方法: 図7

  1. 「開発者の設定」リンクをクリックします。 これにより、Windowsマシンの設定アプリが開きます。
  2. 以下に示すように開発者モードのトグルをオンにします。

.NET MAUIでQRコードを生成する方法: 図8

開発者モードがオンになったらプロジェクトを実行します。 次のウィンドウが表示されます:

.NET MAUIでQRコードを生成する方法: 図9

これは、プロジェクトを作成したときにVisual Studio 2022によって自動的に作成されるテンプレートアプリケーションです。 次に、IronBarcodeをインストールし、必要に応じてコードを変更します。

IronBarcodeのインストール

IronBarcodeをインストールするには、NuGetパッケージマネージャーコンソールを開きます。 Visual Studioでパッケージマネージャーコンソールを開くには、次の手順に従います。

  1. WindowsマシンでVisual Studioを起動します。
  2. 作業したいプロジェクトを開くか、新しいプロジェクトを作成します。
  3. Visual Studioメニューの「Tools」に移動します。
  4. ドロップダウンメニューで「NuGet パッケージマネージャー」をクリックします。
  5. もう一つのドロップダウンメニューが表示され、「パッケージ マネージャー コンソール」を選択します。

これにより、プロジェクトのNuGetパッケージを管理するためのコマンドラインインターフェースを持つパッケージマネージャーコンソールウィンドウが開きます。 パッケージマネージャーコンソールに次のコマンドを入力してIronBarcodeをインストールします。

Install-Package BarCode

これにより、IronBarcodeライブラリがプロジェクトに追加され、利用可能になります。

.NET MAUIでQRコードを生成する方法: 図10

IronBarcodeを使用した.NET MAUI QRコードジェネレータ

それでは、独自のQRコードジェネレータモバイルアプリケーションを作成するためのコードを書きましょう。 画面に生成されたQRコードを表示するには、.NET MAUIの機能を活用します。 MainPage.xamlファイルを開き、次のコードに置き換えます。

<?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="QrCodeGeneratorMAUI.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Label
                Text="Hello!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="Welcome to QR Code Generator .NET Multi-platform App UI"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to QR Code Generator dot Net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Entry x:Name="qrCodeText"
                   Placeholder="Enter QR Code"/>

            <Image
                x:Name="qrCodeImage"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Generate QR Code"
                Clicked="OnButtonClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
<?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="QrCodeGeneratorMAUI.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Label
                Text="Hello!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="Welcome to QR Code Generator .NET Multi-platform App UI"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to QR Code Generator dot Net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Entry x:Name="qrCodeText"
                   Placeholder="Enter QR Code"/>

            <Image
                x:Name="qrCodeImage"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Generate QR Code"
                Clicked="OnButtonClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
XML

上記のXAMLコードはQRコードを生成する.NET MAUIページを表しています。 ここに.NET MAUIコンポーネントの簡単な説明があります:

  • <Label>: 画面にテキストを表示します。 このアプリケーションでは、挨拶メッセージと見出しを表示し、ユーザーに情報と指示を提供します。
  • <Entry>: ユーザーにテキスト入力フィールドを提供します。 このアプリケーションでは、ユーザーがQRコードにエンコードしたいコンテンツを入力できます。
  • <Image>: 画面に画像を表示します。 このアプリケーションでは、ユーザーが生成ボタンをクリックした後に生成されたQRコード画像を表示します。
  • <Button>: クリック可能なボタンを表します。 クリックされるとアクションをトリガーします。 このアプリケーションでは、ユーザーが<Entry>フィールドに入力したコンテンツに基づいてQRコードの生成を開始します。

これらのコンポーネントが連携して、ユーザーがテキストを入力し、ボタンをクリックし、対応するQRコードを画面に表示するインターフェースを作成します。

では、QRコードを生成するためのバックエンドコードを書きましょう。 MainPage.xaml.csファイルを開き、コードビハインドクラスを次のように更新します。

using IronBarCode;

namespace QrCodeGeneratorMAUI
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnButtonClicked(object sender, EventArgs e)
        {
            // Get the text from the entry field
            string text = qrCodeText.Text;

            // Generate the QR code using the IronBarcode library
            var qrCode = QRCodeWriter.CreateQrCode(text);

            // Convert the QR code to binary JPEG data
            var qrCodeBytes = qrCode.ToJpegBinaryData();

            // Set the QR code image source to display the generated QR code on the UI
            qrCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));
        }
    }
}
using IronBarCode;

namespace QrCodeGeneratorMAUI
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnButtonClicked(object sender, EventArgs e)
        {
            // Get the text from the entry field
            string text = qrCodeText.Text;

            // Generate the QR code using the IronBarcode library
            var qrCode = QRCodeWriter.CreateQrCode(text);

            // Convert the QR code to binary JPEG data
            var qrCodeBytes = qrCode.ToJpegBinaryData();

            // Set the QR code image source to display the generated QR code on the UI
            qrCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));
        }
    }
}
Imports IronBarCode

Namespace QrCodeGeneratorMAUI
	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub OnButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
			' Get the text from the entry field
			Dim text As String = qrCodeText.Text

			' Generate the QR code using the IronBarcode library
			Dim qrCode = QRCodeWriter.CreateQrCode(text)

			' Convert the QR code to binary JPEG data
			Dim qrCodeBytes = qrCode.ToJpegBinaryData()

			' Set the QR code image source to display the generated QR code on the UI
			qrCodeImage.Source = ImageSource.FromStream(Function() New MemoryStream(qrCodeBytes))
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

コードの説明です。

  1. OnButtonClickedメソッドは、ボタンのクリックイベントのイベントハンドラーです。 ボタンがクリックされると、このメソッドが実行されます。
  2. OnButtonClickedメソッドの内部で、qrCodeTextエントリーフィールドに含まれるテキストはtext変数に割り当てられます。
  3. QRCodeWriter.CreateQrCode(text)は、入力されたテキストに基づいてQRコードを作成します。
  4. qrCode.ToJpegBinaryData()は、QRコードをバイナリJPEGデータに変換します。
  5. qrCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes))は、生成されたQRコード画像を表示するためにqrCodeImageコントロールのソースを設定します。

.NET MAUIアプリケーションを実行する

機能をテストするためにプロジェクトを実行しましょう。 F5キーを押してWindowsマシンでアプリケーションを実行します。プロジェクトを実行すると、次の画面が表示されます。

エンコードしたいテキストを入力し、QRコード生成ボタンを押します。 QRコードが生成され、以下に示すように画面に表示されます。

.NET MAUIでQRコードを生成する方法: 図11

注釈とQRコード値の追加

これまで、基本機能を備えたQRコードジェネレータを開発しました。 次に、QRコードの注釈とQRコード値を追加して、より機能的にしましょう。 OnButtonClickedメソッドを以下のソースコードに示すように変更します。

private void OnButtonClicked(object sender, EventArgs e)
{
    // Get the text from the entry field
    string text = qrCodeText.Text;

    // Generate the QR code using the IronBarcode library
    var qrCode = QRCodeWriter.CreateQrCode(text);

    // Add the text of the QR code value below the generated barcode
    qrCode.AddBarcodeValueTextBelowBarcode();

    // Add an annotation text above the barcode
    qrCode.AddAnnotationTextAboveBarcode("My QR Code Generated by .NET MAUI App");

    // Convert the QR code to binary JPEG data
    var qrCodeBytes = qrCode.ToJpegBinaryData();

    // Set the QR code image source to display the generated QR code on the UI
    qrCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));
}
private void OnButtonClicked(object sender, EventArgs e)
{
    // Get the text from the entry field
    string text = qrCodeText.Text;

    // Generate the QR code using the IronBarcode library
    var qrCode = QRCodeWriter.CreateQrCode(text);

    // Add the text of the QR code value below the generated barcode
    qrCode.AddBarcodeValueTextBelowBarcode();

    // Add an annotation text above the barcode
    qrCode.AddAnnotationTextAboveBarcode("My QR Code Generated by .NET MAUI App");

    // Convert the QR code to binary JPEG data
    var qrCodeBytes = qrCode.ToJpegBinaryData();

    // Set the QR code image source to display the generated QR code on the UI
    qrCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));
}
Private Sub OnButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
	' Get the text from the entry field
	Dim text As String = qrCodeText.Text

	' Generate the QR code using the IronBarcode library
	Dim qrCode = QRCodeWriter.CreateQrCode(text)

	' Add the text of the QR code value below the generated barcode
	qrCode.AddBarcodeValueTextBelowBarcode()

	' Add an annotation text above the barcode
	qrCode.AddAnnotationTextAboveBarcode("My QR Code Generated by .NET MAUI App")

	' Convert the QR code to binary JPEG data
	Dim qrCodeBytes = qrCode.ToJpegBinaryData()

	' Set the QR code image source to display the generated QR code on the UI
	qrCodeImage.Source = ImageSource.FromStream(Function() New MemoryStream(qrCodeBytes))
End Sub
$vbLabelText   $csharpLabel
  • qrCode.AddBarcodeValueTextBelowBarcode()は、生成されたバーコードの下にQRコード値のテキストを追加します。
  • qrCode.AddAnnotationTextAboveBarcode("My QR Code Generated by .NET MAUI App")は、バーコードの上に注釈テキストを追加し、それが.NET MAUIアプリによって生成されたことを示します。

Visual Studio 2022は.NET MAUIアプリ向けにホットリロードオプションを提供します。OnButtonClickedメソッドを変更した後、ホットリロードをクリックすると、変更が表示されます; アプリケーションを閉じて再ビルドする必要はないかもしれません。

エンコードしたいテキストを入力し、QRコード生成ボタンを押します。 QRコードは以下に示すように生成されます。

.NET MAUIでQRコードを生成する方法: 図12 - Qrコードジェネレータ

IronBarcode provides other useful functionality such as adding images, coloring and resizing the QR code, etc. For more detailed tutorials and code examples, you may refer to their official documentation.

.NET MAUIバーコードジェネレータ

IronBarcodeライブラリを使用して.NET MAUIバーコードジェネレータを作成することもできます。 コードを少し変更するだけで、以下のコード例に示すように問題なく動作させることができます。

private void OnButtonClicked(object sender, EventArgs e)
{
    // Get the text from the entry field
    string text = barCodeText.Text;

    // Generate the barcode using the IronBarcode library with Code128 encoding
    var barCode = BarcodeWriter.CreateBarcode(text, BarcodeEncoding.Code128);

    // Add the text of the barcode value below the generated barcode
    barCode.AddBarcodeValueTextBelowBarcode();

    // Add an annotation text above the barcode
    barCode.AddAnnotationTextAboveBarcode("My Barcode Generated by .NET MAUI App");

    // Convert the barcode to binary JPEG data
    var qrCodeBytes = barCode.ToJpegBinaryData();

    // Set the barcode image source to display the generated barcode on the UI
    barCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));
}
private void OnButtonClicked(object sender, EventArgs e)
{
    // Get the text from the entry field
    string text = barCodeText.Text;

    // Generate the barcode using the IronBarcode library with Code128 encoding
    var barCode = BarcodeWriter.CreateBarcode(text, BarcodeEncoding.Code128);

    // Add the text of the barcode value below the generated barcode
    barCode.AddBarcodeValueTextBelowBarcode();

    // Add an annotation text above the barcode
    barCode.AddAnnotationTextAboveBarcode("My Barcode Generated by .NET MAUI App");

    // Convert the barcode to binary JPEG data
    var qrCodeBytes = barCode.ToJpegBinaryData();

    // Set the barcode image source to display the generated barcode on the UI
    barCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));
}
Private Sub OnButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
	' Get the text from the entry field
	Dim text As String = barCodeText.Text

	' Generate the barcode using the IronBarcode library with Code128 encoding
	Dim barCode = BarcodeWriter.CreateBarcode(text, BarcodeEncoding.Code128)

	' Add the text of the barcode value below the generated barcode
	barCode.AddBarcodeValueTextBelowBarcode()

	' Add an annotation text above the barcode
	barCode.AddAnnotationTextAboveBarcode("My Barcode Generated by .NET MAUI App")

	' Convert the barcode to binary JPEG data
	Dim qrCodeBytes = barCode.ToJpegBinaryData()

	' Set the barcode image source to display the generated barcode on the UI
	barCodeImage.Source = ImageSource.FromStream(Function() New MemoryStream(qrCodeBytes))
End Sub
$vbLabelText   $csharpLabel

出力

.NET MAUIでQRコードを生成する方法: 図13 - バーコードジェネレータ

.NET MAUIとIronBarcodeライブラリを使用してQRコードジェネレータを作成する方法を学ぶことに加え、IronBarcodeの価格設定についても言及する価値があります。

IronBarcode is free for development and offers a 無料トライアルや商業目的に応じた異なる価格プランを提供しています。 価格設定は、オンプレミス展開に対する永久ライセンスや、クラウドベース展開に対するサブスクリプションベースライセンスを含むライセンスオプションに基づいています。

.NET MAUIでQRコードを生成する方法: 図14

結論

この記事では、.NET MAUIとIronBarcodeライブラリを使用してQRコードジェネレータとバーコードジェネレータを作成する方法を学びました。 IronBarcodeをインストールし、QRコードを作成し、.NET MAUIのイメージコントロールを使用して画面に表示する手順を探りました。

.NET MAUIはクロスプラットフォームアプリケーションを構築するための強力なフレームワークを提供し、IronBarcodeはバーコードとQRコードの生成を簡素化します。 これらの技術を組み合わせることで、現代のデバイスの能力を活用した柔軟かつ効率的なアプリケーションを作成することができます。

よくある質問

.NET MAUIとは何ですか、またXamarin Formsとどう違うのですか?

.NET MAUI(Multi-platform App UI)は、Xamarin Formsフレームワークの進化形であり、単一のコードベースで複数のプラットフォーム用にネイティブユーザーインターフェースを構築できるようにします。Android、iOS、macOS、Windowsなどをサポートし、Xamarin Formsと比較して効率的な開発体験を提供します。

.NET MAUIアプリケーションでQRコードを生成するにはどうすればよいですか?

.NET MAUIアプリケーションでQRコードを生成するには、IronBarcodeライブラリを使用します。まず、NuGetを介してIronBarcodeを追加し、MAUIユーザーインターフェースを構成し、IronBarcodeのCreateQrCodeメソッドを使用して文字列からQRコードを生成します。

Visual Studioで.NET MAUIプロジェクトをセットアップする手順は何ですか?

Visual Studio 2022で.NET MAUIプロジェクトをセットアップするには、Visual Studioを開き、新しいプロジェクトを作成し、MAUIテンプレートを検索して.NET MAUIアプリテンプレートを選択し、Visual Studioによって提供されるセットアップ手順に従います。

.NET MAUIアプリケーションでQRコードを表示するにはどうすればよいですか?

.NET MAUIアプリケーションでQRコードを表示するには、IronBarcodeのCreateQrCodeメソッドを使用してQRコードを生成し、ToJpegBinaryDataを使用してバイナリデータに変換します。その後、UIにImageコントロールを使用して表示できます。

.NET MAUIプロジェクトでQRコードに注釈を追加できますか?

はい、IronBarcodeを使って.NET MAUIプロジェクトでQRコードに注釈を追加できます。QRコードの上や下にテキスト注釈を追加するために、AddBarcodeValueTextBelowBarcodeAddAnnotationTextAboveBarcodeのようなメソッドを使用します。

.NET MAUIアプリケーションでIronBarcodeは無料で使用できますか?

IronBarcodeは開発目的には無料で利用でき、無料トライアルが提供されています。商業利用には、プロジェクトのニーズに応じて選べる様々な価格プランとライセンシングオプションがあります。

.NET MAUIを使ってバーコードジェネレーターを作成するにはどうすればよいですか?

.NET MAUI でバーコードジェネレーターを作成するには、QR コード生成コードを変更して IronBarcode ライブラリを使用できます。希望のエンコーディングを使用して BarcodeWriter.CreateBarcode メソッドを使い、さまざまなタイプのバーコードを生成してください。

.NET MAUIでIronBarcodeを使用する利点は何ですか?

.NET MAUIでIronBarcodeを使用することにより、開発者は単一のコードベースで複数のプラットフォームで効率的にバーコードとQRコードの生成と操作ができます。カスタマイズ可能なサイズ、誤り訂正、エンコーディングオプションなどの強力な機能を提供し、クロスプラットフォームアプリケーションの可能性を向上させます。

Jordi Bardia
ソフトウェアエンジニア
Jordiは、最も得意な言語がPython、C#、C++であり、Iron Softwareでそのスキルを発揮していない時は、ゲームプログラミングをしています。製品テスト、製品開発、研究の責任を分担し、Jordiは継続的な製品改善において多大な価値を追加しています。この多様な経験は彼を挑戦させ続け、興味を持たせており、Iron Softwareで働くことの好きな側面の一つだと言います。Jordiはフロリダ州マイアミで育ち、フロリダ大学でコンピュータサイエンスと統計学を学びました。