需要从文本中生成QR码。我正在使用ZXing.unity.dll库
using ZXing;
using ZXing.QrCode;
生成QR码
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);
}
问题2:我不是很确定,但是下面的示例应该创建一个透明的背景:
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;
}