Android 生成豎直方向的條形碼
阿新 • • 發佈:2018-12-17
有橫向的條形碼,也有豎直方向的條形碼.
怎麼把條形碼豎起來呢?
1.旋轉裝著條形碼的view
此方法不可行 因為view的寬高和二維碼的bitmap的寬高是相反的啊.這樣的話即使旋轉了,view裡顯示的圖形會非常小.不行.
2.生成條形碼的bitmap的時候,就要寬高和容器寬高一致.
此方法可行,只要在生成條形碼bitmap之後,逆時針旋轉90度,得到新的bitmap就行了.
程式碼:
public static Bitmap getBarcodeBitmapVertical(String content, int qrWidth, int qrHeight) { //文字的高度 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); canvas.save(); //旋轉 Matrix matrix = new Matrix(); matrix.setRotate(-90, (float) bigBitmap.getWidth() / 2, (float) bigBitmap.getHeight() / 2); Bitmap dstbmp = Bitmap.createBitmap(bigBitmap, 0, 0, bigBitmap.getWidth(), bigBitmap.getHeight(), matrix, true); return dstbmp; } catch (Exception e) { LogUtil.d("bitmap 旋轉失敗!"); return null; } }