我找不到任何可以使用的 Xamarin Forms 条码扫描器的源代码。是否有使用 zxing 库的可用于 Xamarin Forms 的条码扫描器示例?
我找不到任何可以使用的 Xamarin Forms 条码扫描器的源代码。是否有使用 zxing 库的可用于 Xamarin Forms 的条码扫描器示例?
您可以尝试使用下面的代码。 将zxing库/组件添加到解决方案中的所有项目
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");
}
}
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);
}
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");
}
};
var scanner = new MobileBarcodeScanner();
var result = await scanner.Scan();
if(result == null)
return;
results.Text = result.Text;