Xamarin forms Barcode Scanner
You can try the code below. Add the zxing library/component to all the projects in the solution
public class Home : ContentPage
{
string message = "";
public Home()
{
//Intialize the button
Button btnScan = new Button
{
Text = "Start Scan",
BackgroundColor = Color.FromRgb(207, 197, 159),
TextColor = Color.White,
BorderRadius = 5,
TranslationY = 120
};
//Attach the click event
btnScan.Clicked += btnScan_Clicked;
this.Content = new StackLayout
{
BackgroundColor = Color.FromRgb(150, 172, 135),
Spacing = 10,
Padding = 25,
Children =
{
btnScan
}
};
}
async void btnScan_Clicked(object sender, EventArgs e)
{
var scanner = new MobileBarcodeScanner();
scanner.TopText = "Hold the camera up to the barcode\nAbout 6 inches away";
scanner.BottomText = "Wait for the barcode to automatically scan!";
//This will start scanning
ZXing.Result result = await scanner.Scan();
//Show the result returned.
HandleResult(result);
}
void HandleResult(ZXing.Result result)
{
var msg = "No Barcode!";
if (result != null)
{
msg = "Barcode: " + result.Text + " (" + result.BarcodeFormat + ")";
}
DisplayAlert("", msg, "Ok");
}
}
You can use ZXing.Net.Mobile.Forms. But you attention.
ZXing.Net.Mobile.Forms current version is 2.4.1. I used this version and build failed on Xamarin.Forms.Android project. => Crash App.
=> I used version 2.3.2. It working fine.
In Android project file MainActivity.cs, you add following code:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
It seems, the tutorial code on here is incorrect
Call scanner:
private async void BtnScan_OnClicked(object sender, EventArgs e) { ZXingScannerPage scanPage = new ZXingScannerPage(); scanPage.OnScanResult += (result) => { scanPage.IsScanning = false; Device.BeginInvokeOnMainThread(() => { Navigation.PopAsync(); EtInputCode.Text = "Code: " + result.Text; }); }; await Navigation.PushAsync(scanPage); }
You can use ZXing.Net.Mobile nuget. The library is available in github in the following URL https://github.com/Redth/ZXing.Net.Mobile. You'll find a usage documentation in the first page. But I'll explain it brievelly in 3 steps as follows :
Add the nuget to your project
Create a ContentPage. In the xaml side, create a button or an image button. In the following exemple, I'm using like an image button like this :
<ImageButton x:Name="ScanButton" Source="scannimage.png" />
In the code bind, put the following code in the constructor or in the
OnAppearing()
method:ScanButton.Clicked += async (sender, e) => { var scanner = new ZXing.Mobile.MobileBarcodeScanner(); var result = await scanner.Scan(); if (result != null) { await DisplayAlert("Code barre", "Scanned Barcode: " + result.Text, "Ok"); } };