com.google.zxing:core 生成二维码的简单使用

时间:2023-01-30 19:53:48
            String content = "";
int size = 240;
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 字符转码格式设置
hints.put(EncodeHintType.ERROR_CORRECTION, "H"); // 容错级别设置 默认为L
hints.put(EncodeHintType.MARGIN, "4"); // 空白边距设置
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints); int[] pixels = new int[size * size];
for(int y = 0; y < size; y++){
for(int x = 0; x < size; x++){
if(bitMatrix.get(x, y)){ // 黑色色块像素设置
pixels[y * size + x] = color_black;
} else { // 白色色块像素设置
pixels[y * size + x] = color_white;
}
}
} Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, size, 0, 0, size, size);

二维码上添加logo

       int logoBitmap = BitmapFactory.decodeResource(context.getResources,R.mipmap.icon_logo);
float logoPercent = 0.2;//logo图片在原图片中的显示大小比例,取值0-1,建议使用0.2,百分比过大可能导致二维码扫描失败
/*获取原图片和Logo图片各自的宽、高值 */
int srcWidth = bitmap.getWidth();
int srcHeight = bitmap.getHeight();
int logoWidth = bitmap.getWidth();
int logoHeight = bitmap.getHeight();
/*计算画布缩放的宽高比 */
float scaleWidth = srcWidth * logoPercent / logoWidth;
float scaleHeight = srcHeight * logoPercent / logoHeight;
/* 使用Canvas绘制,合成图片 */
Bitmap addLogBitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(addLogBitmap);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.scale(scaleWidth, scaleHeight, srcWidth/2, srcHeight/2);
canvas.drawBitmap(logoBitmap, srcWidth/2 - logoWidth/2, srcHeight/2 - logoHeight/2, null);

在二维码底部添加文字

        String text = "底部文字";
int srcWidth = bitmap.getWidth();
int srcHeight = bitmap.getHeight();
Bitmap addTextBitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(addTextBitmap);
canvas.drawBitmap(bitmap, 0, 0, null); Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
textPaint.setTextSize(14.0f);
textPaint.setTypeface(Typeface.DEFAULT_BOLD); // 采用默认的宽度
textPaint.setColor(Color.BLACK);
canvas.drawText(text, srcWidth/2 - textPaint.measureText(text)/2, srcHeight - 8, textPaint);