Android開發實現二維碼生成
阿新 • • 發佈:2018-11-10
要根據內容來實現二維碼的生成,這裡需要用到一個第三方的jar包(Google的開源jar包zxing.jar)
下面直接貼上我寫好的最最最簡單的demo
public Bitmap setCode(String contents,int width,int height){ HashMap hints=new HashMap(); hints.put(EncodeHintType.CHARACTER_SET,"utf-8"); //指定字元編碼為“utf-8” //hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //二維碼糾錯等級為中級 hints.put(EncodeHintType.MARGIN, 1); //設定圖片的邊距 QRCodeWriter qrCodeWriter = new QRCodeWriter();//獲得一個寫二維碼的物件 try { //定義一個矩陣,接收生成的二維碼,這裡根據傳進來的寬(width)高(height)和內容(contents)來生成二維碼 BitMatrix bitMatrix = qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE,width,height,hints); //定義一個大小為二維碼寬高的陣列,畫出其中每一位的顏色(畫二維碼) int[] arr = new int[width * height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (bitMatrix.get(j, i)) { arr[i * width + j] = 0x00000000; } else { arr[i * width + j] = 0xffffffff; } } } //使用Bitmap的createBitmap方法將arr陣列建立為一個位圖 return Bitmap.createBitmap(arr,0,width,width,height,Bitmap.Config.RGB_565); } catch (WriterException e) { e.printStackTrace(); } return null; }
在使用時,只需要呼叫這個方法,傳入二維碼的內容和寬高即可,方法返回的型別是一個位圖,接收到點陣圖後再將點陣圖設定到圖片控制元件上就可以看到生成的二維碼了