c# - 使用 Xamarin.Forms 和 Zxing 生成二维码

标签 c# xamarin xamarin.ios xamarin.forms qr-code

我在网上看到了很多关于此的信息(旧帖子),但似乎对我没有任何用处。 我正在尝试从字符串中生成二维码并将其显示在应用程序中。

这是我一开始的想法

qrCode = new ZXingBarcodeImageView
{
    BarcodeFormat = BarcodeFormat.QR_CODE,
    BarcodeOptions = new QrCodeEncodingOptions
    {
        Height  = 50,
        Width   = 50
    },
    BarcodeValue = codeValue,
    VerticalOptions = LayoutOptions.CenterAndExpand,
    HorizontalOptions = LayoutOptions.CenterAndExpand
};

这在 Android 上运行良好,但在 IOS 设备上根本无法呈现。 所以在研究之后我试着这样做:

Image qrCode;

if (Device.OS == TargetPlatform.iOS)
{
    var writer = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,
        Options = new ZXing.Common.EncodingOptions
        {
            Width = 50,
            Height = 50
        }
    };

    var b = writer.Write(codeValue);

    qrCode = new Image
    {
        Aspect = Aspect.AspectFill,
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand,
        Source = ImageSource.FromStream(() =>
        {
            MemoryStream ms = new MemoryStream(b);
            ms.Position = 0;
            return ms;
        })
    };

}else{
    qrCode = new ZXingBarcodeImageView
    {
        BarcodeFormat = BarcodeFormat.QR_CODE,
        BarcodeOptions = new QrCodeEncodingOptions
        {
            Height  = 50,
            Width   = 50
        },
        BarcodeValue = codeValue,
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand
    };
}

Content = new StackLayout
{
    Children = {
        header, lblExplenationText, qrCode
    },
    BackgroundColor = Color.White
};

但是仍然没有渲染任何东西。

ZXing.Mobile.Forms NuGet 包版本:2.1.47(最新)

最佳答案

好像是已知的issue .
幸运的是有一个解决方法,设置一个HeightRequest & WidthRequest,这里是一个工作代码示例:

ZXingBarcodeImageView GenerateQR(string codeValue)
{
    var qrCode = new ZXingBarcodeImageView
    {
        BarcodeFormat = BarcodeFormat.QR_CODE,
        BarcodeOptions = new QrCodeEncodingOptions
        {
            Height = 350,
            Width = 350
        },
        BarcodeValue = codeValue,
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand
    };
    // Workaround for iOS
    qrCode.WidthRequest = 350;
    qrCode.HeightRequest = 350;
    return qrCode;
}

关于c# - 使用 Xamarin.Forms 和 Zxing 生成二维码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42532733/

相关文章:

c# - 按子集合中的属性对父实体进行排序

mvvm - 是否可以使用 Fluent API 在 mvvmcross 中进行方法绑定(bind)?

ios - IOS 中的 Resource.designer 等价物

c# - Xamarin iOS ObserveOrientationDidChange 横向或纵向

xamarin - 基于跨多个文件的其他样式的样式

c# - 基于聚类点计数的颜色聚类特征

c# - 在 C# 中连接来自两个数据库的表

c# - RavenDB 使用 JsonIgnore 属性存储属性

c# - ASP.NET ThreadPool.QueueUserWorkItem Common.Logging 到 NLog 导致 IIS 崩溃 - Bug 或者只是我?

c# - 为什么滚动这个 xamarin 页面这么慢?