二維碼的應用非常廣泛,用途也很多,網上也有很多實用的精簡包可以引入,本篇主要記錄了不用引入新的module,自己集成生成二維碼功能的過程。
一、引入依賴
首先在libs文件目錄下放進jar包zxing.jar,然後引入依賴,sync。
implementation files('libs/zxing.jar')
也可以在file/project structure/app/dependencies中點擊+號選擇添加jar包
二、集成工具類
然後添加二維碼工具類EncodingUtils.class
package com.example.qrcodedemo.utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.HashMap;
import java.util.Map;
/**
* 二維碼生成工具類
*/
public class EncodingUtils {
/**
* 創建二維碼
*
* @param content content
* @param widthPix widthPix
* @param heightPix heightPix
* @param logoBm logoBm
* @return 二維碼
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || "".equals(content)) {
return null;
}
// 配置參數
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容錯級別
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 圖像數據轉換,使用了矩陣轉換
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面這裏按照二維碼的算法,逐個生成二維碼的圖片,
// 兩個for循環是圖片橫列掃描的結果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二維碼圖片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
//必須使用compress方法將bitmap保存到文件中再進行讀取。直接返回的bitmap是沒有任何壓縮的,內存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 在二維碼中間添加Logo圖案
*/
private static Bitmap addLogo(Bitmap src, Bitmap logo) {
if (src == null) {
return null;
}
if (logo == null) {
return src;
}
//獲取圖片的寬高
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int logoWidth = logo.getWidth();
int logoHeight = logo.getHeight();
if (srcWidth == 0 || srcHeight == 0) {
return null;
}
if (logoWidth == 0 || logoHeight == 0) {
return src;
}
//logo大小爲二維碼整體大小的1/5
float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try {
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
canvas.save();
canvas.restore();
} catch (Exception e) {
bitmap = null;
e.getStackTrace();
}
return bitmap;
}
}
三、使用
修改佈局文件用於預覽二維碼效果,其中EditText用於輸入放在二維碼中的文本信息,qrCode1爲生成不帶logo的二維碼的點擊事件,qrCode2爲生成帶logo的二維碼的點擊事件。
<?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"
android:orientation="vertical">
<EditText
android:id="@+id/input_txt"
android:layout_width="300dp"
android:textSize="18sp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="輸入要生成二位碼的內容"/>
<Button
android:text="生成二維碼"
android:layout_width="239dp"
android:layout_height="wrap_content"
android:id="@+id/encode_btn1"
android:textSize="18sp"
android:onClick="qrCode1"
android:layout_marginTop="20dp"/>
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/code_image1"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="10dp"
android:background="#7e7b7b"/>
<Button
android:text="生成帶Logo的二維碼"
android:layout_width="239dp"
android:layout_height="wrap_content"
android:id="@+id/encode_btn2"
android:textSize="18sp"
android:onClick="qrCode2"
android:layout_marginTop="10dp"/>
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/code_image2"
android:layout_marginTop="20dp"/>
</LinearLayout>
然後我們在主活動中使用集成的EncodingUtils類中的createQRCode()方法來生成相應的二維碼,第一個參數content爲二維碼中所存放的信息,第二個參數widthPix爲所生成二維碼的寬度,第三個參數heightPix爲所生成二維碼的高度,第四個參數logoBm爲二維碼中間的logo,如果不帶logo的話此參數設爲null即可。
package com.example.qrcodedemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.qrcodedemo.utils.EncodingUtils;
public class MainActivity extends AppCompatActivity {
private ImageView enCodeImage1,enCodeImage2;//展示生成的二維碼
private EditText editText;//輸入要生成二維碼的內容
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
enCodeImage1 = (ImageView) findViewById(R.id.code_image1);
enCodeImage2 = (ImageView) findViewById(R.id.code_image2);
editText = (EditText) findViewById(R.id.input_txt);
}
/**
* 生成不帶Logo的二維碼點擊事件
* @param view
*/
public void qrCode1(View view){
if ("".equals(editText.getText().toString())){
Toast.makeText(this, "請在輸入框中輸入內容", Toast.LENGTH_SHORT).show();
return;
}
//生成二維碼
Bitmap codeBitmap = EncodingUtils.createQRCode(editText.getText().toString(),500,500,null);
enCodeImage1.setImageBitmap(codeBitmap);//顯示二維碼
}
/**
* 生成帶Logo的二維碼
* @param view
*/
public void qrCode2 (View view){
if ("".equals(editText.getText().toString())){
Toast.makeText(this, "請在輸入框中輸入內容", Toast.LENGTH_SHORT).show();
return;
}
//獲取logo資源,
//R.drawable.logo爲logo圖片
Bitmap logoBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
//生成二維碼
Bitmap codeBitmap = EncodingUtils.createQRCode(editText.getText().toString(),500,500,logoBitmap);
enCodeImage2.setImageBitmap(codeBitmap);//顯示二維碼
}
}
效果如下:
源代碼:qrcodeDemo
jar包路徑:zxing.jar,點擊clone/下載,選擇下載zip包即可獲得項目文件,zxing.jar包在“你的下載位置\wd23-qrcodeDemo-master.zip\qrcodeDemo\app\libs”目錄下
有幫助的話請點贊喔,筆芯~