當前位置:編程學習大全網 - 編程語言 - 在android開發中 什麽庫可以識別DM二維碼

在android開發中 什麽庫可以識別DM二維碼

1.1 準備工作

如果我們只做二維碼的生成,那麽只需要添加核心jar包即可,

1.2 二維碼生成

OK,添加完jar包之後我們就可以開始寫二維碼生成代碼了,二維碼本身就是壹張Bitmap圖片,所以我們這裏主要就是看怎麽樣來生成這張圖片,我在主界面添加壹個按鈕和壹個ImageView,當點擊按鈕時生成壹張二維碼圖片顯示在ImageView上。布局如下:

[java] view plain copy print?

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

xmlns:android="/apk/res/android"

xmlns:tools="/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="org.mobiletrain.qrwriter.MainActivity">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="generate"

android:text="生成二維碼"/>

<ImageView

android:id="@+id/iv"

android:layout_width="256dp"

android:layout_height="256dp"

android:layout_centerInParent="true"/>

</RelativeLayout>

當我點擊按鈕時生成二維碼圖片,那我們就來看看生成二維碼圖片的核心代碼:

[java] view plain copy print?

private Bitmap generateBitmap(String content,int width, int height) {

QRCodeWriter qrCodeWriter = new QRCodeWriter();

Map<EncodeHintType, String> hints = new HashMap<>();

hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

try {

BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

int[] pixels = new int[width * height];

for (int i = 0; i < height; i++) {

for (int j = 0; j < width; j++) {

if (encode.get(j, i)) {

pixels[i * width + j] = 0x00000000;

} else {

pixels[i * width + j] = 0xffffffff;

}

}

}

return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);

} catch (WriterException e) {

e.printStackTrace();

}

return null;

}

首先這個方法接收三個參數,這三個參數分別表示生成二維碼的文本內容(妳要把哪壹個文本用二維碼圖片表示出來),第二個和第三個參數分別表示生成的二維碼圖片的寬和高。在這裏,我們首先要獲得壹個QRCodeWriter實例,該實例中有壹個方法叫做encode,通過該方法對文本內容進行編碼,該方法***有五個參數,第壹個參數表示生成二維碼的文本內容,第二個參數表示編碼格式,第三個參數表示生成的二維碼的寬度,第四個參數表示生成的二維碼的高度,第五個參數可選,可以用來設置文本的編碼,encode方法的返回值是壹個BitMatrix,妳可以把BitMatrix理解成壹個二維數組,這個二維數組的每壹個元素都表示壹個像素點是否有數據。OK,接下來我們需要定義壹個int數組用來存放Bitmap中所有像素點的顏色,可是我們又怎麽知道每壹個像素點是什麽顏色呢?這個時候就需要我們遍歷BitMatrix了,如果BitMatrix上的點表示 該點有數據,那麽對應在Bitmap上的像素點就是黑色,否則就是白色。BitMatrix中的get方法的返回值為壹個boolean類型,true表示該點有數據,false表示該點沒有數據。通過兩個嵌套的for循環將BitMatrix遍歷壹遍,然後給pixels數組都賦上值,OK,pixels數組有值之後,接下來調用Bitmap的createBitmap方法創建壹個Bitmap出來就可以了,createBitmap方法***接收6個參數,第壹個參數表示Bitmap中所有像素點的顏色,第二個參數表示像素點的偏移量,第三個參數表示Bitmap每行有多少個像素點,第四個參數表示生成的Bitmap的寬度,第五個參數表示生成的Bitmap的高度,第六個參數表示生成的Bitmap的色彩模式,因為二維碼只有黑白兩種顏色,所以我們可以不用考慮透明度,直接使用RGB_565即可。OK,這樣的話我們就獲取到了二維碼的圖片了,最後我們再來看看點擊事件:

[java] view plain copy print?

public void generate(View view) {

Bitmap qrBitmap = generateBitmap("",400, 400);

iv.setImageBitmap(qrBitmap);

}

  • 上一篇:學而思在安徽哪些地方有分校
  • 下一篇:我的世界怎麽對抗蜘蛛 各種攻擊性生物的解析
  • copyright 2024編程學習大全網