小微型企业网站建立,网络公司门头,怎么做可以聊天的网站,福泉网站制作Android生成二维码通常使用ZXing库#xff0c;其中提供了QRCodeWriter类。QRCodeWriter可将字符串编译为位矩阵BitMatrix#xff0c;然后我们可以将位矩阵转为Int数组#xff0c;通过bitmap.setPixels()方法将数组绘制于位图上。
1. 添加依赖
//Gradle Scripts - buil…Android生成二维码通常使用ZXing库其中提供了QRCodeWriter类。QRCodeWriter可将字符串编译为位矩阵BitMatrix然后我们可以将位矩阵转为Int数组通过bitmap.setPixels()方法将数组绘制于位图上。
1. 添加依赖
//Gradle Scripts - build.gradle(Module:app)
implementation com.google.zxing:core:3.4.1
implementation com.journeyapps:zxing-android-embedded:4.2.0
2. 工具类
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
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 QRCodeUtils {/*** 根据文本与容错值生成二维码位图* param text 文本* param errorCorrectionLevel 容错值* return 返回位图如无文本内容返回null*/public Bitmap getQRBitmap(String text, ErrorCorrectionLevel errorCorrectionLevel) {if(textnull){return null;}//错误值if(errorCorrectionLevelnull){errorCorrectionLevelErrorCorrectionLevel.H;}int width text.length() * 6; // 二维码图片的宽度if(errorCorrectionLevelErrorCorrectionLevel.L){width (int) (width*1.5);}else if(errorCorrectionLevelErrorCorrectionLevel.Q){width (int) (width*2);}else if(errorCorrectionLevelErrorCorrectionLevel.M){width (int) (width*3);}else if(errorCorrectionLevelErrorCorrectionLevel.H){width (int) (width*4);}int height width; // 二维码图片的高度int margin 1; // 二维码图片的空白边距MapEncodeHintType, Object hints new HashMap();hints.put(EncodeHintType.MARGIN, margin); // 设置空白边距hints.put(EncodeHintType.CHARACTER_SET, UTF-8); // 设置字符编码格式hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel); // 设置容错率try {// 根据配置参数生成位矩阵对象BitMatrix bitMatrix new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);// 创建像素数组并根据位矩阵对象为数组元素赋色值int[] pixels new int[width * height];for (int y 0; y height; y) {for (int x 0; x width; x) {if (bitMatrix.get(x, y)) { // 返回true表示黑色色块pixels[y * width x] Color.BLACK;} else { // 返回false表示白色色块pixels[y * width x] Color.WHITE;}}}// 创建位图对象并根据像素数组设置每个像素的色值Bitmap bitmap Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);bitmap.setPixels(pixels, 0, width, 0, 0, width, height);//过小放大if(width500){float i500/width;Matrix matrixnew Matrix();matrix.setScale(i,i);bitmap Bitmap.createBitmap(bitmap,0,0,width,height,matrix,false);}return bitmap;} catch (WriterException e) {e.printStackTrace();return null;}}
}3. 容错率
容错率即二维码允许损毁量。
ErrorCorrectionLevel.H 30%
ErrorCorrectionLevel.M 25%
ErrorCorrectionLevel.Q 15%
ErrorCorrectionLevel.L 7%