Android 生成條形碼 生成下方帶文字的條形碼
阿新 • • 發佈:2018-12-16
可以使用Zxing來獲得條形碼的bitmap. 1.繪製帶有文字的條形碼 由於直接不能繪製出帶有文字的條形碼. 我想到的解決方案是 需要繪製的條形碼的高度的 3/4給條形碼 1/4給文字. 先繪製條形碼 得到bitmap 在建立bitmap 在底部繪製文字,合併兩個bitmap. 2.繪製不帶文字的條形碼,只需要把繪製文字和bigbitmap去掉就行了. 3.使用程式碼需要先引入Zxing庫 import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.yiersan.wmsclient.utils.LogUtil; import java.util.EnumMap; import java.util.Map; /** * 使用Zxing生成二維碼 */ public class Barcode { private static final int WHITE = 0xFFFFFFFF; private static final int BLACK = 0xFF000000; /** * * @param content 文字內容 * @param qrWidth 條形碼的寬度 * @param qrHeight 條形碼的高度 * @return bitmap */ public static Bitmap getBarcodeBitmap(String content, int qrWidth, int qrHeight) { content = content.trim(); //文字的高度 int mHeight = qrHeight / 4; try { Map<EncodeHintType, Object> hints = new EnumMap(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.MARGIN, 1); BitMatrix result; try { result = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, qrWidth, mHeight * 3, hints); } catch (IllegalArgumentException iae) { return null; } int width = result.getWidth(); int height = result.getHeight(); 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] = result.get(x, y) ? BLACK : 0; } } Bitmap qrBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); qrBitmap.setPixels(pixels, 0, width, 0, 0, width, height); //大的bitmap Bitmap bigBitmap = Bitmap.createBitmap(width, qrHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bigBitmap); Rect srcRect = new Rect(0, 0, width, height); Rect dstRect = new Rect(0, 0, width, height); canvas.drawBitmap(qrBitmap, srcRect, dstRect, null); Paint p = new Paint(); p.setColor(Color.BLACK); p.setFilterBitmap(true); //字型大小 p.setTextSize(mHeight); //開始繪製文字的位置 canvas.translate(width / 10, mHeight); canvas.drawText(content, 0, content.length(), 0, height, p); return bigBitmap; } catch (Exception e) { return null; } } }