依赖
1
| implementation("com.google.zxing:core:3.4.1")
|
调用示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import android.graphics.Bitmap; import android.graphics.Color;
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix;
import java.util.Map;
public class Test {
public Bitmap createBitmap(String contents, int width, int height)throws WriterException {
BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = matrix.get(x, y) ? Color.BLACK : Color.WHITE; } }
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } }
|
上面这样创建的是默认样式的二维码,白色边框会比较大,这是个小问题。
更多的自定义参数在 Map<EncodeHintType,?> hints
这个参数设置,看以下示例:
1 2 3 4 5 6 7 8
| ... Map<EncodeHintType,Object> hints = new HashMap<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//容错率最高 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 字符编码 UTF-8 hints.put(EncodeHintType.MARGIN, 0);//白边大小
BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints); ...
|
这样设置的就是一个没有白边的二维码