繁体   English   中英

如何使用 ZXing.Net lib 修复 QR 码生成

[英]How to fix QR code generation using ZXing.Net lib

需要从文本中生成二维码。 我正在使用ZXing.unity.dll

using ZXing;
using ZXing.QrCode;

生成二维码

private static Color32[] Encode(string textForEncoding, int width, int height) {
    var writer = new BarcodeWriter {
        Format = BarcodeFormat.QR_CODE,

        Options = new QrCodeEncodingOptions{
            Height = height,
            Width = width
        }
    };
return writer.Write(textForEncoding);
}
public Texture2D generateQR(string text) {
    var encoded = new Texture2D (256, 256);
    var color32 = Encode(text, encoded.width, encoded.height);
    encoded.SetPixels32(color32);
    encoded.Apply();
    return encoded;
}

将生成的 QR 应用于字段中填写的 RawImage

public RawImage RI;
...
RI.texture = generateQR("https://test.link/123");

输出是带有大白边的图片。

二维码预览图

  • Q1 - 如何去除白边;
  • Q2 - 如何制作透明背景;
  • Q3 - 如何将黑色更改为任何其他颜色

Q3:改变前景色和背景色的示例:

private static Color32[] Encode(string textForEncoding, int width, int height)
{
    var writer = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,

        Options = new QrCodeEncodingOptions
        {
            Height = height,
            Width = width
        },
        Renderer = new Color32Renderer
        {
            Background = new Color32(255, 0, 0, 0),
            Foreground = new Color32(0, 255, 0, 0)
        }
    };
    return writer.Write(textForEncoding);
}

Q2:我不确定,但以下示例应该创建一个透明背景:

private static Color32[] Encode(string textForEncoding, int width, int height)
{
    var writer = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,

        Options = new QrCodeEncodingOptions
        {
            Height = height,
            Width = width
        },
        Renderer = new Color32Renderer
        {
            Background = new Color32(0, 0, 0, 255)
        }
    };
    return writer.Write(textForEncoding);
}

Q1:创建尽可能小的没有边框的图像并手动调整大小

private static Color32[] Encode(string textForEncoding, int width, int height)
{
    var writer = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,

        Options = new QrCodeEncodingOptions
        {
            Height = width,
            Width = height,
            Margin = 0
        }
    };
    return writer.Write(textForEncoding);
}
public Texture2D generateQR(string text)
{
    // create the image as small as possible without a white border by setting width an height to 1
    var color32 = Encode(text, 1, 1);
    var widthAndHeight = color32.Length / 2;
    var encoded = new Texture2D(widthAndHeight, widthAndHeight);
    encoded.SetPixels32(color32);
    encoded.Apply();
    //
    // Attention: insert code for resizing to the desired size here
    // I didn't try it myself. Not sure if it works.
    //
    encoded.Resize(256, 256);
    return encoded;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM