服务与支持
Service and support
开发打印方面,如何实现左边二维码右边文字(或者2个二维码并排打印)?
2022-06-29 发布者:群索科技

这种需求比较常见,目前市面上的机器基本上都只有文字、图片的打印方法可调用,但单纯的打印文字、图片是无法实现文字图片并排打印的,只能考虑使用图片方式实现,思路如下:


把文字生成图片,然后和二维码图片左右合并成一张,再调用打印图片的方法,将合成的图片打印出来,这样即可达到目的,另外需要注意,图片左右合并时候,需要2张图片高度一致,否则低的一边会出现黑边,同理,上下合并则需要2张图片宽度一致


1. 附参考方法:

/**

* 文字转图片

* @param text 将要生成图片的内容

* @param textSize 文字大小

* @return

*/

  public static Bitmap textAsBitmap(String text, float textSize) {


TextPaint textPaint = new TextPaint();


textPaint.setColor(Color.BLACK);


textPaint.setTextSize(textSize);


StaticLayout layout = new StaticLayout(text, textPaint, 380,

Alignment.ALIGN_NORMAL, 1.3f, 0.0f, true);

Bitmap bitmap = Bitmap.createBitmap(layout.getWidth() + 20,

layout.getHeight() + 20, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bitmap);

canvas.translate(10, 10);

canvas.drawColor(Color.WHITE);


layout.draw(canvas);

Log.d("textAsBitmap",

String.format("1:%d %d", layout.getWidth(), layout.getHeight()));

return bitmap;

}


/**

* 两张图片左右合并成一张

*

* @param bitmap1

* @param bitmap2

* @return

*/

public Bitmap twoBtmap2One1(Bitmap bitmap1, Bitmap bitmap2) {

Bitmap bitmap3 = Bitmap.createBitmap(bitmap1.getWidth()+bitmap2.getWidth(),

bitmap1.getHeight() , bitmap1.getConfig());

Canvas canvas = new Canvas(bitmap3);

canvas.drawBitmap(bitmap1, new Matrix(), null);

canvas.drawBitmap(bitmap2,bitmap1.getWidth(), 0, null);

return bitmap3;

}


// 缩放图片

public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {

// 获得图片的宽高

int width = bm.getWidth();

int height = bm.getHeight();

// 计算缩放比例

float scaleWidth = ((float) newWidth) / width;

float scaleHeight = ((float) newHeight) / height;

// 取得想要缩放的matrix参数

Matrix matrix = new Matrix();

matrix.postScale(scaleWidth, scaleHeight);

// 得到新的图片

Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,

true);

return newbm;

}


深圳市群索科技有限公司


电话:0755-23280616/23280696


邮箱:info@szqunsuo.com


网址:www.szqunsuo.com


地址:广东省深圳市西乡航城工业区富鑫林工业园C栋4楼