xamarin - 在Xamarin表单PCL中,xamarin.android ZXing二维码生成

  显示原文与译文双语对照的内容
119 5

我试图用ZXing包来生成和显示二维代码,我尝试了下面的代码,我不能显示二维代码。它显示空白图像( 透明的) 。

private void OnGenerateQRCodeButton_Clicked(object sender, EventArgs e)
 {
 var writer = new BarcodeWriter
 {
 Format = BarcodeFormat.QR_CODE,
 Options = new EncodingOptions
 {
 Height = (int)imageCompanyLogo.Height,
 Width = (int) imageCompanyLogo.Width,
 Margin = 0,
 PureBarcode = true
 }
 };
 var bitmap = writer.Write("www.helloworld.com");
 imageQRCode.Source = ImageSource.FromStream(() => new MemoryStream(bitmap));
 }

请提出任何方法。谢谢。

时间:原作者:0个回答

140 1

调试并查看流是否处于空状态。

var stream = (Stream)null;
private void OnGenerateQRCodeButton_Clicked(object sender, EventArgs e)
{
 var writer = new BarcodeWriter
 {
 Format = BarcodeFormat.QR_CODE,
 Options = new EncodingOptions
 {
 Height = (int)imageCompanyLogo.Height,
 Width = (int) imageCompanyLogo.Width,
 Margin = 0,
 PureBarcode = true
 }
 };
 using(var bitmap = barcodeWriter.Write("www.helloworld.com"))
 {
 stream = new MemoryStream();
 bitmap.Save(stream, ImageFormat.Png);
 stream.Seek(0, SeekOrigin.Begin);
 }
 imageQRCode.Source = ImageSource.FromStream(() => new MemoryStream(stream));
 }
原作者:
87 0
  • 在 PCL(Xamarin) 项目中为依赖项服务创建接口。
  • 在 Native(Xamarin.Droid) 中创建类并从PCL接口继承。

实现如下所示的方法。

public Stream ConvertImageStream(string text, int width = 300, int height = 300)
{
 var barcodeWriter = new ZXing.Mobile.BarcodeWriter
 {
 Format = ZXing.BarcodeFormat.QR_CODE,
 Options = new ZXing.Common.EncodingOptions
 {
 Width = width,
 Height = height,
 Margin = 10
 }
 };
 barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
 var bitmap = barcodeWriter.Write(text);
 var stream = new MemoryStream();
 bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);//this is the diff between iOS and Android
 stream.Position = 0;
 return stream;
}
  • 使用依赖项服务从 PCL(Xamarin) 项目调用方法。

在 xaml.cs 中

private void OnGenerateQRCodeButton_Clicked(object sender, EventArgs e)
{
 string barcodeText ="www.helloworld.com";
 var stream = DependencyService.Get<IBarCodeServices>().ConvertImageStream(barcodeText, (int)imageCompanyLogo.Width,(int) imageCompanyLogo.Height);
 barcodeImage.Source = ImageSource.FromStream(() => stream);
}
原作者:
...