首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何创建和实现用于CustomOverlay扫描仪的ZXing?

如何创建和实现用于CustomOverlay扫描仪的ZXing?
EN

Stack Overflow用户
提问于 2019-08-01 06:57:49
回答 1查看 3.4K关注 0票数 1

我在Xamarin.Forms项目中使用Xamarin.Forms条形码扫描器插件。根据一些帖子,我需要使用自定义覆盖ZXing扫描仪,以便有取消按钮。但我对Xamarin.Forms项目中的Android开发并不熟悉。

到目前为止,我知道扫描仪(MobileBarcodeScanner of ZXing plugin)接受Android.Views.View作为覆盖,以取代默认的扫描页面视图。

代码语言:javascript
运行
复制
public async Task<string> ScanAsync()
{
    MobileBarcodeScanner scanner = new MobileBarcodeScanner();
    scanner.UseCustomOverlay = true;
    scanner.CustomOverlay = ???????;

    var scanResult = await scanner.Scan();
    if (scanResult != null)
    { return scanResult.Text; }
    return null;
}

但我不知道如何创建视图页面(无论是在XML中还是以编程方式)并将其设置为scanner.CustomOverlay。

我不确定一个普通的Android视图是否可以用于扫描仪,任何详细的引用都会得到真正的认可。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-01 09:07:52

如果您想要自定义覆盖,您必须为每个平台创建自己的视图。您可以像这样定制您的覆盖(创建一个名为ZxingOverlayView的自定义覆盖,将其设置为scanner.CustomOverlay):

代码语言:javascript
运行
复制
var scanner = new ZXing.MobileMobileBarcodeScanner();
scanner.UseCustomOverlay = true;
myCustomOverlayInstance = new ZxingOverlayView(this, scanner);
scanner.CustomOverlay = myCustomOverlayInstance;

ZxingOverlayView应该继承view,然后将控件添加到自定义视图中。您可以看到有关此链接的详细信息。

http://slackshotindustries.blogspot.com/2013/04/creating-custom-overlays-in-xzing.html

编辑

完全有步骤。

首先,您可以为依赖服务创建一个接口。

代码语言:javascript
运行
复制
 public interface IDeviceService
  {
    Task<string> ScanAsync();
  }

您可以在PCL代码中使用此接口。

代码语言:javascript
运行
复制
  private async void DependencyButton_Clicked(object sender, EventArgs e)
    {
        var result = await DependencyService.Get<IDeviceService>().ScanAsync();
        if (!string.IsNullOrEmpty(result))
        {
            await DisplayAlert(result, null, "OK");
        }
    }

在android平台上。你可以设计你的布局。首先,创建一个布局

代码语言:javascript
运行
复制
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:id="@+id/imgClose"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:src="@drawable/close"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="20dp"/>
  <RelativeLayout
    android:id="@+id/llScan"
    android:layout_width="240dp"
    android:layout_height="240dp"
    android:layout_centerInParent="true"
    android:background="@drawable/scan">
  <ImageView
        android:id="@+id/imgLine"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/scan_line"
        android:layout_centerHorizontal="true" />
     </RelativeLayout>
  <View
    android:id="@+id/viewTop"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/llScan"
    android:background="@color/title_black"/>
 <View
    android:id="@+id/viewBottom"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/llScan"
    android:background="@color/title_black"
    android:layout_alignParentBottom="true"/>
 <View
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/viewTop"
    android:layout_toLeftOf="@id/llScan"
    android:layout_above="@id/viewBottom"
    android:background="@color/title_black"/>
 <View
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/viewTop"
    android:layout_above="@id/viewBottom"
    android:layout_toRightOf="@id/llScan"
    android:background="@color/title_black"/>
 </RelativeLayout>

然后实现依赖服务接口,并使用您的新布局。

代码语言:javascript
运行
复制
 [assembly: Xamarin.Forms.Dependency(typeof(DeviceService))]
 namespace Sample.Droid
 {
  public class DeviceService : IDeviceService
 {
    public async Task<string> ScanAsync()
    {
        var scanner = new ZXing.Mobile.MobileBarcodeScanner
        {
            UseCustomOverlay = true

        };
        //scanner.CustomOverlay = new CustomScanView(Application.Context);
        var options = new ZXing.Mobile.MobileBarcodeScanningOptions()
        {
            TryHarder = true,
            AutoRotate = false,
            UseFrontCameraIfAvailable = false,
            CameraResolutionSelector = new CameraResolutionSelectorDelegate(SelectLowestResolutionMatchingDisplayAspectRatio),
            PossibleFormats = new List<ZXing.BarcodeFormat>()
            {
                ZXing.BarcodeFormat.QR_CODE
            }
        };

        View scanView = LayoutInflater.From(Application.Context).Inflate(Resource.Layout.ScanView, null);
        ImageView imgLine = scanView.FindViewById<ImageView>(Resource.Id.imgLine);
        ImageView imgClose = scanView.FindViewById<ImageView>(Resource.Id.imgClose);
        imgClose.Click += delegate
        {
            scanner.Cancel();
        };
        scanner.CustomOverlay = scanView;

        ObjectAnimator objectAnimator = ObjectAnimator.OfFloat(imgLine, "Y", 0, DpToPixels(240));
        objectAnimator.SetDuration(2500);
        objectAnimator.RepeatCount = -1;
        objectAnimator.SetInterpolator(new LinearInterpolator());
        objectAnimator.RepeatMode = ValueAnimatorRepeatMode.Restart;
        objectAnimator.Start();

        ZXing.Result scanResults = await scanner.Scan(CrossCurrentActivity.Current.Activity, options);
        if (scanResults != null)
        {
            return scanResults.Text;
        }
        return string.Empty;
    }

    private int DpToPixels(double dp)
    {
        return (int)(dp * Application.Context.Resources.DisplayMetrics.Density);
    }

    private CameraResolution SelectLowestResolutionMatchingDisplayAspectRatio(List<CameraResolution> availableResolutions)
    {
        CameraResolution result = null;
        //a tolerance of 0.1 should not be visible to the user
        double aspectTolerance = 0.1;
        var displayOrientationHeight = DeviceDisplay.MainDisplayInfo.Orientation == DisplayOrientation.Portrait ? DeviceDisplay.MainDisplayInfo.Height : DeviceDisplay.MainDisplayInfo.Width;
        var displayOrientationWidth = DeviceDisplay.MainDisplayInfo.Orientation == DisplayOrientation.Portrait ? DeviceDisplay.MainDisplayInfo.Width : DeviceDisplay.MainDisplayInfo.Height;
        //calculatiing our targetRatio
        var targetRatio = displayOrientationHeight / displayOrientationWidth;
        var targetHeight = displayOrientationHeight;
        var minDiff = double.MaxValue;
        //camera API lists all available resolutions from highest to lowest, perfect for us
        //making use of this sorting, following code runs some comparisons to select the lowest resolution that matches the screen aspect ratio and lies within tolerance
        //selecting the lowest makes Qr detection actual faster most of the time
        foreach (var r in availableResolutions.Where(r => Math.Abs(((double)r.Width / r.Height) - targetRatio) < aspectTolerance))
        {
            //slowly going down the list to the lowest matching solution with the correct aspect ratio
            if (Math.Abs(r.Height - targetHeight) < minDiff)
                minDiff = Math.Abs(r.Height - targetHeight);
            result = r;
        }
        return result;
    }
   }

}

IOS代码。

代码语言:javascript
运行
复制
[assembly: Xamarin.Forms.Dependency(typeof(DeviceService))]
namespace Sample.iOS
{
public class DeviceService : IDeviceService
{
    public async Task<string> ScanAsync()
    {
        var scanner = new ZXing.Mobile.MobileBarcodeScanner()
        {
            UseCustomOverlay = true
        };

        var options = new ZXing.Mobile.MobileBarcodeScanningOptions()
        {
            TryHarder = true,
            AutoRotate = false,
            UseFrontCameraIfAvailable = false,
            PossibleFormats = new List<ZXing.BarcodeFormat>()
            {
                ZXing.BarcodeFormat.QR_CODE
            }
        };

        ScannerOverlayView customOverlay = new ScannerOverlayView();
        customOverlay.OnCancel += () =>
        {
            scanner?.Cancel();
        };
        customOverlay.OnResume += () =>
        {
            scanner?.ResumeAnalysis();
        };
        customOverlay.OnPause += () =>
        {
            scanner?.PauseAnalysis();
        };
        scanner.CustomOverlay = customOverlay;


        ZXing.Result scanResults = null;
        scanResults = await scanner.Scan(options);
        //customOverlay.Dispose();
        if (scanResults != null)
        {
            return scanResults.Text;
        }
        return string.Empty;
    }
}

这是运行GIF的。

这里有一个很好的简单代码。你可以参考一下。Xamarin

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57303386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档