Zxing使用

来源:互联网 发布:兔先森男装百货铺淘宝 编辑:程序博客网 时间:2024/04/29 11:31

转载请标明出处


将zxinglib作为module导入as中,使其关联成相应module的依赖类库

扫描二维码:

Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent,1);

 

protected void onActivityResult(int requestCode, intresultCode, Intent data) {
     if(resultCode == RESULT_OK) {
           Bundlebundle = data.getExtras();
          StringscanResult = bundle.getString("result");
         contentTv.setText(scanResult);
    }
}

 

生成二维码:

String input =contentEt.getText().toString();
if (!TextUtils.isEmpty(input)) {
    Hashtable<EncodeHintType,String> hints = new Hashtable<EncodeHintType, String>();
    hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
    //图像数据转换,使用了矩阵转换
    BitMatrix bitMatrix = null;
    try {
        Log.d("test","11111111111111111111111111");
        bitMatrix = newQRCodeWriter().encode(input, BarcodeFormat.QR_CODE,QR_WIDTH,QR_HEIGHT,hints);
        int[] pixels = new int[QR_WIDTH* QR_HEIGHT];
        //下面这里按照二维码的算法,逐个生成二维码的图片,
        //两个for循环是图片横列扫描的结果
        for (int y = 0; y < QR_HEIGHT;y++)
        {
            for (int x = 0; x < QR_WIDTH;x++)
            {
                if (bitMatrix.get(x, y))
                {
                    pixels[y * QR_WIDTH+ x] = 0xff000000;
                }
                else
                {
                    pixels[y * QR_WIDTH+ x] = 0xffffffff;
                }
            }
        }
        //生成二维码图片的格式,使用ARGB_8888
        Bitmap bitmap= Bitmap.createBitmap(QR_WIDTH,QR_HEIGHT, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, QR_WIDTH,0, 0, QR_WIDTH, QR_HEIGHT);
        //显示到一个ImageView上面
        imageIv.setImageBitmap(bitmap);
    } catch (WriterException e) {
        e.printStackTrace();
    }

}

 

0 0