Android 生成竖直方向的条形码

上篇记了Android使用Zxing生成下方带文本的条形码:https://blog.csdn.net/qq_25452989/article/details/83276726

这篇是得到竖向的条形码.

如图:有横向的条形码,也有竖直方向的条形码.

怎么把条形码竖起来呢?

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值