Exemplo n.º 1
0
        public BarcodeScannerRenderer(Context context) : base(context)
        {
            MainLayout =
                (ConstraintLayout)LayoutInflater.FromContext(context).Inflate(Resource.Layout.BarcodeTracker, null);
            AddView(MainLayout);
            CameraSourcePreview       = MainLayout.FindViewById <CameraSourcePreview>(Resource.Id.preview);
            CloseScannerButton        = MainLayout.FindViewById <ImageButton>(Resource.Id.closeScannerBtn);
            CloseScannerButton.Click += async delegate
            {
                await Xamarin.Forms.Application.Current.MainPage.Navigation.PopModalAsync();
            };

            MGraphicOverlay = MainLayout.FindViewById <GraphicOverlay>(Resource.Id.faceOverlay);

            BarcodeDetector detector = new BarcodeDetector.Builder(Application.Context)
                                       .Build();

            detector.SetProcessor(
                new MultiProcessor.Builder(new GraphicBarcodeTrackerFactory(MGraphicOverlay, this)).Build());

            if (!detector.IsOperational)
            {
                // Note: The first time that an app using barcode API is installed on a device, GMS will
                // download a native library to the device in order to do detection.  Usually this
                // completes before the app is run for the first time.  But if that download has not yet
                // completed, then the above call will not detect any barcodes.
                //
                // IsOperational can be used to check if the required native library is currently
                // available.  The detector will automatically become operational once the library
                // download completes on device.
                Android.Util.Log.Warn(TAG, "Barcode detector dependencies are not yet available.");
            }
            MCameraSource = new CameraSource.Builder(Application.Context, detector)
                            .SetAutoFocusEnabled(true)
                            .SetFacing(Android.Gms.Vision.CameraFacing.Back)
                            .SetRequestedFps(15.0f)
                            .Build();

            var torchFab      = FindViewById <FloatingActionButton>(Resource.Id.fab_torchlight);
            var hasFlashlight = Context.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFlash);

            if (!hasFlashlight)
            {
                torchFab.Hide();
            }
            else
            {
                torchFab.Click += TorchFab_Click;
            }
            StartCameraSource();
        }
        private void Init()
        {
            mStartRequested   = false;
            mSurfaceAvailable = false;

            mAppIdProcessor = new BarcodeDetectorProcessor(this);

            mBarcodeDetector = new BarcodeDetector.Builder(Context)
                               .SetBarcodeFormats(BarcodeFormat.QrCode)
                               .Build();
            mBarcodeDetector.SetProcessor(mAppIdProcessor);

            mCameraBuilder = new CameraSource.Builder(Context, mBarcodeDetector)
                             .SetFacing(CameraFacing.Back)
                             .SetAutoFocusEnabled(true)
                             .SetRequestedFps(30.0f);

            mSurfaceView = new SurfaceView(Context);
            mSurfaceView.Holder.AddCallback(new SurfaceCallback(this));
            AddView(mSurfaceView);
        }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            // 스케너 사용 가능여부 확인
            if (!CheckScannerStatus())
            {
                return;
            }

            if (CameraSource == null && Element.Width > 0 && Element.Height > 0)
            {
                // 바코드 검출 객체 설정 및 콜백 등록
                BarcodeDetector = new BarcodeDetector
                                  .Builder(Context)
                                  .SetBarcodeFormats(Element.BarcodeFormats.ToVisionFormat())
                                  .Build();
                BarcodeDetector.SetProcessor(this);
                this.Write("BarcodeDetector is created");

                // 프리뷰어 사이즈 얻기
                var previewerSize = Element.GetPreviewSize(Resources.DisplayMetrics);
                this.Write($"Previewer size - Width : {previewerSize.Width}, Height : {previewerSize.Height}");

                // 카메라 소스 생성
                CameraSource = new CameraSource
                               .Builder(Context, BarcodeDetector)
                               .SetFacing(CameraFacing.Back)
                               .SetRequestedPreviewSize(previewerSize.Width, previewerSize.Height)
                               .SetRequestedFps(10.0f)
                               .Build();
                this.Write("CameraSource is created");
            }

            switch (e.PropertyName)
            {
            case "IsTorchOn":
            {
                try
                {
                    if (Element.IsScanning && Camera != null)
                    {
                        var parameters = Camera.GetParameters();
                        parameters.FlashMode = Element.IsTorchOn ? TorchOn : TorchOff;
                        Camera.SetParameters(parameters);

                        this.Write($"IsTorchOn : {Element.IsTorchOn}");
                    }
                }
                catch (Exception ex)
                {
                    this.Write($"Camera exception : {ex.Message}, IsTorchOn : {Element.IsTorchOn}");
                }
                break;
            }

            case "IsPreviewing":
            case "IsScanning":
            {
                try
                {
                    if (Element.IsScanning && Element.IsPreviewing)
                    {
                        CameraSource?.Start(Control.Holder);
                        Camera = CameraSource?.GetCamera();
                        SetAutoFocusCallback();
                    }
                    else
                    {
                        Element.SetValue(BarcodeScanner.IsTorchOnProperty, false);
                        CameraSource?.Stop();
                    }
                }
                catch (Exception ex)
                {
                    var toggleValue = e.PropertyName == "IsScanning"
                                ? Element.IsScanning
                                : Element.IsPreviewing;

                    this.Write($"CameraSource exception : {ex.Message}, {e.PropertyName} : {toggleValue}");
                }

                this.Write($"{e.PropertyName} : {Element.IsScanning}");
                break;
            }
            }
        }
        public override void OnBindElements(View view)
        {
            try
            {
                CameraPreview            = view.FindViewById <SurfaceView>(Resource.Id.CameraPreview);
                CameraPreviewProgressBar = view.FindViewById <ProgressBar>(Resource.Id.CameraPreviewProgressBar);
                Vibrator  = (Vibrator)Activity.GetSystemService(Context.VibratorService);
                _callback = Arguments.GetBoolean(Constants.Callback);

                if (_callback)
                {
                    _onBarcodeReadListener = NavigationManager.LastFragment as IOnBarcodeReadListener;
                }

#if DEBUG
                _scannedBarcode = Guid.NewGuid().ToString();
                var token = CancelAndSetTokenForView(CameraPreview);
                if (!_callback)
                {
                    Task.Run(async() =>
                    {
                        var result = await ProductService.GetProductByBarcode(_scannedBarcode, token);

                        if (result.Error.Any())
                        {
                            var message = Resources.GetString(Resource.String.ProductBarcodeNotFound);
                            ShowToastMessage(message);

                            return;
                        }

                        RunOnUiThread(() =>
                        {
                            NavigationManager.GoToProductDetails(result.Data);
                        });
                    }, token);
                }
                else
                {
                    NavigationManager.GoToPrevious();
                }
#else
                var barcodeFormats = Arguments.GetIntArray(Constants.BarcodeFormats)
                                     .Cast <BarcodeFormat>()
                                     .Aggregate((acc, barfor) => acc | barfor);

                BarcodeDetector = new BarcodeDetector.Builder(Context)
                                  .SetBarcodeFormats(barcodeFormats)
                                  .Build();

                CameraSource = new CameraSource
                               .Builder(Context, BarcodeDetector)
                               .SetRequestedPreviewSize(640, 480)
                               .SetFacing(CameraFacing.Back)
                               .Build();

                BarcodeDetector.SetProcessor(this);

                CameraPreview.Holder.AddCallback(this);
                CameraPreviewProgressBar.Visibility = ViewStates.Invisible;
#endif
            }
            catch (System.Exception ex)
            {
                ShowToastMessage(ex.Message, ToastLength.Long);

                NavigationManager.GoToPrevious();
            }
        }