我正在使用ZXing生成QR码。这就是我的代码:
public partial class QRPage : ContentPage
{
public QRPage()
{
InitializeComponent();
var stream = DependencyService.Get<IBarcodeService>().ConvertImageStream("nika");
qrImage.Source = ImageSource.FromStream(() => { return stream; });
qrImage.HeightRequest = 200;
}
}
另一部分:
[assembly: Xamarin.Forms.Dependency(typeof(BarcodeService))]
namespace MyApp.Droid
{
public class BarcodeService : IBarcodeService
{
public Stream ConvertImageStream(string text, int width = 500, int height = 500)
{
var barcodeWriter = new ZXing.Mobile.BarcodeWriter
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Width = width,
Height = height,
Margin = 2
}
};
barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
var bitmap = barcodeWriter.Write(text);
var stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Position = 0;
return stream;
}
}
}
这是我正在使用代码的xaml:
<StackLayout Padding="20,30,20,30">
<Label Text="..." FontSize="Medium "/>
<Frame VerticalOptions="CenterAndExpand">
<Image x:Name="qrImage" WidthRequest="300" />
</Frame>
...
</StackLayout>
问题是,无论我为ConvertImageStream
设置了什么样的高度和宽度,结果图像都不是正方形,而是看起来像这样:
如何将其变成正方形?提前谢谢。
答案 0 :(得分:2)
您的代码正确且图片尺寸正确:
我通过保存加倍检查:
var filePath = System.IO.Path.Combine(Environment.ExternalStorageDirectory.AbsolutePath, "qrcode.png");
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Png, 100, fileStream);
}
然后拉它并检查它的大小:
$ adb pull /sdcard/qrcode.png
[100%] /sdcard/qrcode.png
$ identify qrcode.png
qrcode.png PNG 500x500 500x500+0+0 8-bit sRGB 2.85KB 0.000u 0:00.000
我的网页代码:
var image = new Image();
var content = new ContentPage
{
BackgroundColor = Color.Red,
Title = "ZXingQRCode",
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "StackOverflow",
FontSize = 40
},
image
}
}
};
MainPage = new NavigationPage(content);
var stream = DependencyService.Get<IBarcodeService>().ConvertImageStream("https://StackOverflow.com");
image.Source = ImageSource.FromStream(() => { return stream; });
image.HeightRequest = 250;
更新
您所看到的Frame
比图像宽,而不是图像本身。更改框架的BackgroundColor
<StackLayout Padding="20,30,20,30">
<Label Text="..." FontSize="Medium" />
<Frame VerticalOptions="CenterAndExpand" BackgroundColor="Red">
<Image x:Name="qrImage" WidthRequest="300" />
</Frame>
</StackLayout>