【Android开发--新手必看篇】Zxing 二维码

    技术2022-07-11  92

    Android笔记

    ​ ——二维码 【若对该知识点有更多想了解的,欢迎私信博主~~】

    二维码:zxing

    制作:

    将jar包引入libs下,并加载

    创建生成和读取二维码的工具类(此处命名为QRCodeUtile)

    生成二维码

    //创建二维码 public Bitmap writeQRCode(int width,int height,String data){ //设置编码格式UTF-8 Hashtable<EncodeHintType,String> ht=new Hashtable<>(); ht.put(EncodeHintType.CHARACTER_SET,"UTF-8"); //定义转换矩阵 BitMatrix bitMatrix=null; try { bitMatrix =new QRCodeWriter().encode(data,BarcodeFormat.QR_CODE,width,height,ht); } catch (WriterException e) { e.printStackTrace(); } int[] pixles=new int[width*height]; //按照二维码的算法,逐个生成二维码的图片,两个for循环是图片横列扫描的结果 for (int y=0;y<height;y++){ for (int x = 0; x < width; x++) { if (bitMatrix.get(x,y)){ pixles[y*width+x]=0xff000000; } else{ pixles[y*width+x]=0xffffffff; } } } //生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888); bitmap.setPixels(pixles,0,width,0,0,width,height); return bitmap; }

    读取二维码

    //读取二维码 public String readQRCode(Bitmap bitmap,int width,int height){ //获取二维码图片的Bitmap int[] pixles=new int[width*height]; bitmap.getPixels(pixles,0,width,0,0,width,height); //从一个ARGB的像素数组转换成一个RGB数据 RGBLuminanceSource source=new RGBLuminanceSource(width,height,pixles); //构造二值图像比特流,使用HybridBinarizer算法解析数据源 BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(source)); //定义二进制字节流读取 Result result= null; try { result = new QRCodeReader().decode(binaryBitmap); } catch (NotFoundException e) { e.printStackTrace(); } catch (ChecksumException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } String data=result.getText(); return data; }
    使用:

    在Activity里布局

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:layout_width="200dp" android:layout_height="200dp" android:id="@+id/qr"/> </LinearLayout>

    绑定控件,制作二维码

    private ImageView qr; private Bitmap bitmap; private int width=100; private int height=100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //绑定控件 qr=findViewById(R.id.qr); //生成二维码 bitmap=new QRCodeUtile().writeQRCode(width,height,"数据"); //将二维码添加到控件里 qr.setImageBitmap(bitmap); }

    长按鼠标触发事件

    //长按鼠标触发事件 qr.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String data=new QRCodeUtile().readQRCode(bitmap,width,height); Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show(); return false; } });
    注:Zxing源码地址:https://github.com/zxing/zxing
    Processed: 0.009, SQL: 10