使用Xamarin.Forms和Zxing生成QR码 [英] Generate QR code with Xamarin.Forms and Zxing
问题描述
我已经在网上看到很多有关此信息的文章(旧帖子),但是似乎没有任何内容适合我. 我正在尝试从字符串中生成QR码并将其显示在应用程序中.
I've seen alot about this online (old posts) but nothing seems to work for me. I'm trying to generate a QR code out of a string and display it in the app.
这就是我刚开始的时候
qrCode = new ZXingBarcodeImageView
{
BarcodeFormat = BarcodeFormat.QR_CODE,
BarcodeOptions = new QrCodeEncodingOptions
{
Height = 50,
Width = 50
},
BarcodeValue = codeValue,
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand
};
这对于Android来说很好用,但在IOS设备上根本无法渲染. 因此,在研究之后,我尝试这样做:
That works fine for Android but on IOS devices its not rendered at all. So after researching i tried to do it like this:
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
};
但是仍然没有任何渲染.
But there is still nothing rendered at all.
ZXing.Mobile.Forms NuGet软件包版本:2.1.47(最新)
ZXing.Mobile.Forms NuGet Package Version: 2.1.47 (newest)
推荐答案
It seems to be a known issue.
Luckily there is a workaround, to set a HeightRequest
& WidthRequest
, here is a working code example:
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;
}
这篇关于使用Xamarin.Forms和Zxing生成QR码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!