java 如何使用 ZXing 库以编程方式在 Android 中生成自定义二维码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42155015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a custom QR code in Android programmatically using ZXing Library?
提问by Auro
I'm using Journeyapp's ZXing Android Embedded libraryfor my android app and I can generate a simple QR code using the following piece of code
我正在为我的 android 应用程序使用Journeyapp 的 ZXing Android 嵌入式库,我可以使用以下代码生成一个简单的二维码
private void init() {
ImageView qrImageView = (ImageView) findViewById(R.id.qr_image_view);
qrImageView.setImageBitmap(generateQRBitMap("a"));
}
private Bitmap generateQRBitMap(final String content) {
Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
try {
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 512, 512, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bmp.setPixel(x , y, bitMatrix.get(x,y) ? Color.BLACK : Color.WHITE);
}
}
return bmp;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
However, I want to be able to generate something as cool as the one given below
Now I know that I may have to write a custom encoder for that, but I really don't know where to begin. The BitMatrix
class always creates a square QR code, but is there anything that I can use to create the odd shapes?
现在我知道我可能必须为此编写一个自定义编码器,但我真的不知道从哪里开始。本BitMatrix
类总是创建一个正方形QR码,但有什么,我可以用它来创建不规则形状?
回答by Hack5
Try creating two QRCodes. One should be random, call it A. One should contain data, B. Enlarge A, and warp it (blur will do). Create a white vector that is transparent for the shape of the image, and white round the edge. Overlay this image onto QRCode A, and then overlay B on top.
尝试创建两个二维码。一个应该是随机的,称之为 A。一个应该包含数据,B。放大 A,并扭曲它(模糊就可以了)。创建一个对图像形状透明的白色矢量,并在边缘周围使用白色。将此图像覆盖在 QRCode A 上,然后将 B 覆盖在顶部。
Hope you work out some code from this, P
希望你能从中找出一些代码,P
P.S. If you do, make it a library!
PS如果你这样做,把它变成一个图书馆!
回答by Hussain KMR Behestee
I found this library QRGenusing ZXing and very easy to use. Whatever, to design at your desire, you may add another image behind of this QR code's Image View.
我发现这个库QRGen使用 ZXing 并且非常易于使用。无论如何,要根据您的意愿进行设计,您可以在此 QR 码的图像视图后面添加另一个图像。
Sample Code for Generating QR Code
生成二维码的示例代码
Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);