Android -条形码的生成
2017-08-30 本文已影响1655人
ZebraWei
主要思路
- 1.导入Zxing包,根据架包MultiFormatWriter类 ,将字符串宽高,计算出一定时间内x,y偏移量 生成对应的黑白图片。
1.客户端代码
Button generateQRCodeButton = (Button) this
.findViewById(R.id.btn_add_qrcode);
generateQRCodeButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
String contentString = qrStrEditText.getText().toString();
if (!contentString.equals("")) {
// 根据字符串生成条形码图片并显示在界面上,第二个参数为图片的大小(350*350)
Bitmap qrCodeBitmap=null;
qrCodeBitmap= BarcodeCreater.creatBarcode(contentString, 120, 60);
bg.setImageBitmap(qrCodeBitmap);
} else {
Toast.makeText(MainActivity.this, "Text can not be empty", Toast.LENGTH_SHORT.show();
}
}
2.条形码生成代码
private static final int BLACK = 0xff000000;
private static final int WHITE = 0xFFFFFFFF;
private static BarcodeFormat barcodeFormat= BarcodeFormat.CODE_128;
public static Bitmap creatBarcode(String contents, int desiredWidth,int desiredHeight) {
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result=null;
try {
result = writer.encode(contents, barcodeFormat, desiredWidth,
desiredHeight);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}