Xamarin.Forms扫描二维码
仅限Android端
Xamarin.Forms v5.0.0.2012
1、安装包:
ZXing.Net.Mobile.Forms v2.4.1
Ideine.ZXing.Net.Mobile v2.4.2
2、Android项目
MainActivity.cs添加如下代码:
MobileBarcodeScanner.Initialize(Application);
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); MobileBarcodeScanner.Initialize(Application); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } }
AssemblyInfo.cs文件添加如下代码:
[assembly: UsesPermission(Android.Manifest.Permission.Camera)] //相机
[assembly: UsesPermission(Android.Manifest.Permission.Flashlight)] //闪光灯
3、页面代码:
<ContentPage.Content> <StackLayout> <Button x:Name="photo" Text="Photo" Clicked="photo_Clicked"/> <Button x:Name="video" Text="Video" Clicked="video_Clicked"/> <Button x:Name="scan" Text="Scan" Clicked="scan_Clicked"/> <Label x:Name="lab" Text="扫描文本"/> </StackLayout> </ContentPage.Content>
4、后台代码:
private async void scan_Clicked(object sender, EventArgs e) { var scanner = new MobileBarcodeScanner(); var result = await scanner.Scan(); if (null != result) { lab.Text = result.Text; } }