我正在尝试为我的应用程序生成二维码。用户将输入一些文本,数据将传递给下一个显示二维码的 Activity 。
这是我的代码。
public class QRgenerator extends AppCompatActivity {
ImageView imageView;
String Qrcode;
public static final int WIDTH = 500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrgenerator);
getID();
Intent intent = getIntent();
Qrcode = intent.getStringExtra("Data");
//creating thread to avoid ANR exception
Thread t = new Thread(new Runnable() {
@Override
public void run() {
//the message to be encoded in the qr code.
try {
synchronized (this) {
wait(5000);
//runonUIthread on the main thread
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Bitmap bitmap = null;
bitmap = encodeasBitmap(Qrcode);
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
;
} //end of catch block
} //end of rum method
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
//method that returns the bitmap image of the QRcode.
public void getID() {
imageView = (ImageView) findViewById(R.id.imageView2);
}
public Bitmap encodeasBitmap(String str) throws WriterException {
BitMatrix result;
try {
result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
} catch (IllegalArgumentException e) {
//unsupported format
return null;
}
int h = result.getHeight();
int w = result.getWidth();
int[] pixels = new int[w * h];
for (int i = 0; i < h; i++) {
int offset = i * w;
for (int j = 0; j < w; j++) {
pixels[offset + j] = result.get(j, i)? R.color.black:R.color.white;
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, 500, 0, 0, w, h);
return bitmap;
}
}
问题是当我按下按钮并转到下一个屏幕时,只出现白色屏幕, ImageView 中也没有 QR 码。可能是什么错误?
最佳答案
public static Bitmap generateQRBitmap(String content, Context context,int flag){
Bitmap bitmap = null;
int width=256,height=256;
QRCodeWriter writer = new QRCodeWriter();
try {
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height);//256, 256
/* int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();*/
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
//bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);//guest_pass_background_color
bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : context.getResources().getColor(R.color.guest_pass_background_color));//Color.WHITE
}
}
} catch (WriterException e) {
e.printStackTrace();
}
return bitmap;
}
关于android - 如何使用Zxing Library生成二维码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41606384/