问题
I'm trying to generate and display QR code using ZXing package, I tried in following code I was not able to show QR code. It's showing blank image (transparent).
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));
}
Please suggest any way to do it. Thanks.
回答1:
Debug and see if stream in empty or not.
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));
}
回答2:
- Create interface in PCL(Xamarin) project for Dependency Service.
- Create a class in Native(Xamarin.Droid) and Inherit from PCL Interface.
Implement the method as shown below.
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; }
- call the method from PCL(Xamarin) project using Dependency Service.
In 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); }
来源:https://stackoverflow.com/questions/39249911/zxing-qr-code-generation-in-xamarin-forms-pcl