一、前言

本文的内容有两个基础:ZXing.Net和ZXing.Net.Mobile

ZXing.Net:ZXing的C#实现,主要封装了各种二维码的编码、解码等跨平台的算法

ZXing.Net.Mobile:对ZXing.Net在xamarin的应用进行了封装,主要实现了摄像头扫描、扫描view、扫描activity、扫描Fragment等

          ZXing.Net.Mobile下载:xamarin组件市场 或者 github

 

二、效果图

 Xamarin.Android-用ZXing实现二维码扫描以及连续扫描    Xamarin.Android-用ZXing实现二维码扫描以及连续扫描   Xamarin.Android-用ZXing实现二维码扫描以及连续扫描

 

三、基本实现

1、弹出新窗口进行扫描

public class MainFragment : Android.Support.V4.App.Fragment
    {
        MobileBarcodeScanner scanner;

        public override View OnCreateView(LayoutInflater inflater, ViewGroup p1, Bundle p2)
        {
            return inflater.Inflate(Resource.Layout.Main, null);
        }

        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            base.OnViewCreated(view, savedInstanceState);

            scanner = new MobileBarcodeScanner(this.Activity);

            this.View.FindViewById<Button>(Resource.Id.btnDefault).Click += btnDefault_Click;
            this.View.FindViewById<Button>(Resource.Id.btnCustom).Click += btnCustom_Click;
        }

        async void btnDefault_Click(object sender, EventArgs e)
        {
            //不使用自定义界面
            scanner.UseCustomOverlay = false;

            //设置上下提示文字
            scanner.TopText = "上面的文字";
            scanner.BottomText = "下面的文字";

            var result = await scanner.Scan();

            HandleScanResult(result);
        }

        async void btnCustom_Click(object sender, EventArgs e)
        {
            View zxingOverlay;
            //使用自定义界面(可以给框内加个动画什么的,这个自由发挥)
            scanner.UseCustomOverlay = true;
            zxingOverlay = LayoutInflater.FromContext(this.Activity).Inflate(Resource.Layout.ZxingOverlay, null);
            scanner.CustomOverlay = zxingOverlay;

            var result = await scanner.Scan();

            HandleScanResult(result);
        }

        void HandleScanResult(ZXing.Result result)
        {
            string msg = "";

            if (result != null && !string.IsNullOrEmpty(result.Text))
                msg = "扫描结果: " + result.Text;
            else
                msg = "扫描取消!";

            this.Activity.RunOnUiThread(() => 
                {
                    Toast.MakeText(this.Activity, msg, ToastLength.Short).Show();
                });
        }
    }
View Code

相关文章: