.NET MAUI で Android のバーコードを読み書きする方法
.NET MAUI (Multi-platform App UI)はXamarin.Formsの後継であり、開発者が.NETを使用してAndroid、iOS、macOS、Windows用のクロスプラットフォームアプリケーションを構築できるようにします。 これは、複数のプラットフォームでシームレスに動作するネイティブユーザーインターフェイスの作成を可能にすることにより、開発プロセスを合理化します。
このBarCode.AndroidパッケージはAndroidにバーコード機能を提供します!
.NET MAUI で Android のバーコードを読み書きする方法
IronBarcode Android パッケージ
このBarCode.Androidパッケージは.NETクロスプラットフォームプロジェクトを通じてAndroidデバイスにバーコード機能を有効にします。 バニラのBarCodeパッケージは必要ありません。
NuGetでインストール
インストールパッケージ BarCode.Android
.NET MAUIプロジェクトの作成
Visual Studioを開き、「新しいプロジェクトを作成」をクリックします。 MAUIを検索し、.NET MAUIアプリを選択して「次へ」をクリックします。
BarCode.Androidライブラリを含める
ライブラリを追加する方法はいくつかあります。 最も簡単なのは、おそらくNuGetを使用することです。
- Visual Studio内で「Dependencies」を右クリックし、「Manage NuGet Packages ...」を選択します。
- 「Browse」タブを選択して「BarCode.Android」を検索します。
- 「BarCode.Android」パッケージを選択して「インストール」をクリックします。
他のプラットフォームとの問題を避けるために、csprojファイルを修正して、Androidプラットフォームをターゲットにした場合だけパッケージを含めるようにします。 これを行うには:
-
プロジェクトの*.csprojファイルを右クリックして「プロジェクトファイルを編集」を選択します。
-
新しいItemGroup要素を作成します。
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true"> <PackageReference Include="BarCode.Android" Version="2025.3.4" /> </ItemGroup>XML -
「BarCode.Android」のPackageReferenceを作成したItemGroup内に移動します。
上記の手順により、iOSなどのプラットフォームでは「BarCode.Android」パッケージが使用されることはありません。 そのためには、代わりにBarCode.iOSをインストールしてください。
Androidバンドルを構成する
Androidが動作するには、Androidバンドルの設定を構成する必要があります。 「.csproj」ファイル内に、Androidバンドルの設定ファイルを指定するための次のエントリを追加してください:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
プロジェクトのルートディレクトリに「BundleConfig.json」という名前のファイルを作成します。 このJSONファイルには、Androidバンドルに必要な設定が含まれており、ライブラリの機能にとって重要です。
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
この設定により、ネイティブライブラリが圧縮されず、Android環境でライブラリが正常に動作するために必要なステップとなります。
アプリインターフェースを設計する
XAMLファイルを更新して、ユーザーがバーコードおよびQRコードを生成するための値を入力できるようにします。 さらに、バーコード読み取り用のドキュメントを選択するボタンを追加します。 以下は例です:
<?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="IronBarcodeMauiAndroid.MainPage">
<VerticalStackLayout Padding="20">
<HorizontalStackLayout>
<CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
<Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
</HorizontalStackLayout>
<Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
<Button Text="Generate and save barcode" Clicked="WriteBarcode" />
<Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
<Button Text="Generate and save QR code" Clicked="WriteQRcode" />
<Button
Text="Read Barcode"
Clicked="ReadBarcode"
Grid.Row="0"
HorizontalOptions="Center"
Margin="20, 20, 20, 10"/>
<ScrollView
Grid.Row="1"
BackgroundColor="LightGray"
Padding="10"
Margin="10, 10, 10, 30">
<Label x:Name="OutputText"/>
</ScrollView>
</VerticalStackLayout>
</ContentPage>
バーコードを読み書きする
上記のMainPage.xamlコードから、チェックボックスが生成されたバーコードおよびQRコードがPDF形式であるかどうかを決定することがわかります。 次に、ライセンスキーを設定します。 このステップでは、試用版または有料ライセンスキーのいずれかを使用してください。
コードはbarcodeInput変数から値をチェックして取得した後、CreateBarcodeメソッドを使用してバーコードを生成します。 最後に、SaveToDownloadsAsyncメソッドを呼び出し、AndroidおよびiOSの両方に適切にファイルを保存します。
iOSでは、ドキュメントをFilesアプリケーションにエクスポートするためにカスタムファイルパスが必要です。
using IronBarCode;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace IronBarcodeMauiAndroid
{
public partial class MainPage : ContentPage
{
public bool IsGeneratePdfChecked
{
get => generatePdfCheckBox.IsChecked;
set
{
generatePdfCheckBox.IsChecked = value;
}
}
public MainPage()
{
InitializeComponent();
// Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
}
private async void WriteBarcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(barcodeInput.Text))
{
// Create a barcode from the text input with the EAN13 encoding.
var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
// Determine the file extension and data format based on the checkbox state.
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Save the generated barcode to the Downloads folder.
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void WriteQRcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(qrInput.Text))
{
// Create a QR code from the text input.
var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
// Determine the file extension and data format based on the checkbox state.
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Save the generated QR code to the Downloads folder.
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void ReadBarcode(object sender, EventArgs e)
{
try
{
var options = new PickOptions
{
PickerTitle = "Please select a file"
};
var file = await FilePicker.PickAsync(options);
OutputText.Text = "";
if (file != null)
{
using var stream = await file.OpenReadAsync();
BarcodeResults result;
if (file.ContentType.Contains("image"))
{
// Read barcodes from an image file.
result = BarcodeReader.Read(stream);
}
else
{
// Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream);
}
string barcodeResult = "";
int count = 1;
// Retrieve and format the barcode reading results.
result.ForEach(x => { barcodeResult += $"Barcode {count}: {x.Value}\n"; count++; });
OutputText.Text = barcodeResult;
}
}
catch (Exception ex)
{
// Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex);
}
}
public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
{
var downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadsPath.AbsolutePath, fileName);
try
{
// Create the directory if it doesn't exist.
if (!Directory.Exists(downloadsPath.AbsolutePath))
{
Directory.CreateDirectory(downloadsPath.AbsolutePath);
}
// Save the file to the Downloads folder.
await File.WriteAllBytesAsync(filePath, fileData);
}
catch (Exception ex)
{
// Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
}
}
}
}Imports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials
Namespace IronBarcodeMauiAndroid
Partial Public Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked() As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(ByVal value As Boolean)
generatePdfCheckBox.IsChecked = value
End Set
End Property
Public Sub New()
InitializeComponent()
' Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
End Sub
Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(barcodeInput.Text) Then
' Create a barcode from the text input with the EAN13 encoding.
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated barcode to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(qrInput.Text) Then
' Create a QR code from the text input.
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated QR code to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
Dim file = Await FilePicker.PickAsync(options)
OutputText.Text = ""
If file IsNot Nothing Then
Dim stream = Await file.OpenReadAsync()
Dim result As BarcodeResults
If file.ContentType.Contains("image") Then
' Read barcodes from an image file.
result = BarcodeReader.Read(stream)
Else
' Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
' Retrieve and format the barcode reading results.
result.ForEach(Sub(x)
barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)
Try
' Create the directory if it doesn't exist.
If Not Directory.Exists(downloadsPath.AbsolutePath) Then
Directory.CreateDirectory(downloadsPath.AbsolutePath)
End If
' Save the file to the Downloads folder.
Await File.WriteAllBytesAsync(filePath, fileData)
Catch ex As Exception
' Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
End Function
End Class
End NamespaceImports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials
Namespace IronBarcodeMauiAndroid
Partial Public Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked() As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(ByVal value As Boolean)
generatePdfCheckBox.IsChecked = value
End Set
End Property
Public Sub New()
InitializeComponent()
' Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
End Sub
Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(barcodeInput.Text) Then
' Create a barcode from the text input with the EAN13 encoding.
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated barcode to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(qrInput.Text) Then
' Create a QR code from the text input.
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated QR code to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
Dim file = Await FilePicker.PickAsync(options)
OutputText.Text = ""
If file IsNot Nothing Then
Dim stream = Await file.OpenReadAsync()
Dim result As BarcodeResults
If file.ContentType.Contains("image") Then
' Read barcodes from an image file.
result = BarcodeReader.Read(stream)
Else
' Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
' Retrieve and format the barcode reading results.
result.ForEach(Sub(x)
barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)
Try
' Create the directory if it doesn't exist.
If Not Directory.Exists(downloadsPath.AbsolutePath) Then
Directory.CreateDirectory(downloadsPath.AbsolutePath)
End If
' Save the file to the Downloads folder.
Await File.WriteAllBytesAsync(filePath, fileData)
Catch ex As Exception
' Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
End Function
End Class
End Namespaceプロジェクトを実行する
これにより、プロジェクトを実行してバーコード機能を使用する方法が示されます。
.NET MAUIアプリプロジェクトをダウンロードする
このガイドの完全なコードをダウンロードできます。これは.zipファイルとして提供され、Visual Studioで.NET MAUIアプリプロジェクトとして開くことができます。
よくある質問
.NET MAUIは何で、Androidでのバーコードスキャンにどのように関連していますか?
.NET MAUI、またはマルチプラットフォームアプリUIは、Xamarin.Formsの後継であり、開発者がクロスプラットフォームアプリケーションを構築できるようにします。BarCode.Androidパッケージは.NET MAUIと統合し、Androidデバイスでのバーコードの読み取りと書き込みを可能にします。
.NET MAUIプロジェクトにBarCode.Androidライブラリをどのように追加しますか?
Visual StudioでNuGetを使用してBarCode.Androidライブラリを追加できます。'Dependencies'を右クリックして、'Manage NuGet Packages'を選択し、'BarCode.Android'を検索して'Install'をクリックします。
BarCode.Androidパッケージは、Android以外のプラットフォームで使用できますか?
BarCode.Androidパッケージは、特にAndroid用に調整されています。iOS用にはBarCode.iOSパッケージを代わりに使用する必要があります。
Android用のみのプロジェクトにBarCode.Androidライブラリを含めるにはどうすればよいですか?
.csprojファイルを編集して、TargetFramework条件を使用し、Androidターゲット時のみBarCode.Androidパッケージ用の条件付きItemGroupを含める必要があります。
AndroidでBarCode.Androidライブラリを使用するのに特定の設定ファイルが必要ですか?
はい、.csprojファイルにAndroidバンドル用の設定ファイルを指定する必要があります。通常は'BundleConfig.json'と名付けられ、ネイティブライブラリが解凍されるようにするものです。
MAUIアプリケーションでIronBarcodeを使用してバーコードを生成し、保存するにはどうすればよいですか?
BarcodeWriterクラスを使用してテキスト入力からバーコードを作成し、フォーマット(PDFまたはPNG)を決定し、それをAndroidとiOSでSaveToDownloadsAsyncのようなメソッドを使用して保存します。
IronBarcodeで生成されたバーコードを保存するためのファイル形式は何がサポートされていますか?
IronBarcodeは、ユーザーがアプリケーション内で選択したPDFまたはPNG形式でバーコードを保存できます。
.NET MAUI AndroidアプリでのQRコード処理においてIronBarcodeはどのように役立ちますか?
IronBarcodeはQRCodeWriterクラスを通じてQRコードの作成と読み取りを可能にし、入力テキストからQRコードを生成したり、ファイルからバーコードデータを読み取る機能を提供します。
.NET MAUIでIronBarcodeを使って始めるためのサンプルプロジェクトはありますか?
はい、ガイドに示されたサンプルコード付きの完全な.NET MAUIアプリプロジェクトをダウンロードでき、迅速に開始することができます。
ファイルからバーコードデータを読み取るためにIronBarcodeはどのような機能を提供していますか?
IronBarcodeは、BarcodeReaderクラスを使用して画像やPDFファイルからバーコードを読み取り、結果をフォーマットしてアプリケーション内で表示します。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。