android – 如何在ZXing中设置位图的大小?

前端之家收集整理的这篇文章主要介绍了android – 如何在ZXing中设置位图的大小?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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的高度和宽度,结果图像都不是方形,而是看起来像这样:

怎么把它变成正方形?提前致谢.

解决方法

您的代码是正确的,图像大小正确:

我通过保存加倍检查:

var filePath = System.IO.Path.Combine(Environment.ExternalStorageDirectory.AbsolutePath,"qrcode.png");
using (var fileStream = new FileStream(filePath,FileMode.Create))
{
    bitmap.Compress(Bitmap.CompressFormat.Png,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;

更新:

你看到的是框架比图像宽,而不是图像本身.更改框架的BackgroundColor

<StackLayout Padding="20,30">
    <Label Text="..." FontSize="Medium" />
    <Frame VerticalOptions="CenterAndExpand" BackgroundColor="Red">
        <Image x:Name="qrImage" WidthRequest="300" />
    </Frame>
</StackLayout>

原文链接:https://www.f2er.com/android/315254.html

猜你在找的Android相关文章