之前做了个pos机的项目,当时因为是给缅甸客户用的,界面用的是缅甸文,但是打印机不支持缅甸文,所以只能以打印图片的方式实现;所以利用canvas直接画小票图片,直接打印图片实现打印功能;下面是利用canvas画图的工具类:
public class ImgUtil {
// public static void saveBitmap(String bitName, Bitmap mBitmap) {
// File f = new File("/sdcard/" + bitName + ".png");
// try {
// f.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
// FileOutputStream fOut = null;
// try {
// fOut = new FileOutputStream(f);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
// try {
// fOut.flush();
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// fOut.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// Log.i("msg", "图片路径:" + f.getAbsolutePath());
// }
/**
* 获取文本的宽度
*
* @param paint
* @param text
* @return
*/
public static int getFontWidth(Paint paint, String text) {
Rect rect = new Rect();
paint.getTextBounds(text, 0, text.length(), rect);
return rect.width();
}
/**
* 获取文本的高度
*
* @param paint
* @param text
* @return
*/
public static int getFontHeight(Paint paint, String text) {
Rect rect = new Rect();
paint.getTextBounds(text, 0, text.length(), rect);
return rect.height();
}
/**
* 获取打印图片的菜品需要打印的高度
*
* @param list
* @param normalFontHeight
* @param perLineDistance
* @return
*/
public static int getProBmpHeight(ArrayList<ProductModel> list,
int normalFontHeight, int perLineDistance, boolean toKitchen) {
int h = 0;
for (int i = 0; i < list.size(); i++) {
//根据菜品文本长度显示多行
int lines = getProShowLine(list.get(i).getProductName());
for (int j = 0; j < lines; j++) {
h = h + normalFontHeight + perLineDistance;
}
//如果是发送到厨房的需要计算备注的高度
if (toKitchen) {
//显示备注
lines = getProShowLine(list.get(i).getChoseLable());
for (int j = 0; j < lines; j++) {
h = h + normalFontHeight + perLineDistance;
}
}
h = h + perLineDistance;//菜品之间距离大点,方便区分
}
return h;
}
/**
* 把pos端小票信息转成图片
*
* @return
*/
public static Bitmap posTickTopBmp(Activity activity, ArrayList<ProductModel> pros) {
Paint paint = new Paint();
paint.setTextSize(30);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
paint.setTypeface(Typeface.DEFAULT_BOLD);
//店铺名称字体的高度
final int restaurantNameHeight = getFontHeight(paint, "店铺");
//小字黑体文本的高度
paint.setTextSize(20);
final int blackFontHeight = getFontHeight(paint, "店铺");
//小字正常字体的高度
paint.setTypeface(Typeface.DEFAULT);
final int normalFontHeight = getFontHeight(paint, "店铺");
//行与行之间的空白距离
final int perLineDistance = 20;
//字体之间的距离
final int perFontDistance = 20;
//可打印图片的最大宽度和高度;
final int bmpWidth = 576, bmpHeight = 436 + 565 + getProBmpHeight(pros, normalFontHeight, perLineDistance, false);
final int topBlank = 100;//电话和日期之间的空白
final int bottomBlank = 200;//底部留白(可能要撕纸,需要留白)
Bitmap bmp = Bitmap.createBitmap(bmpWidth, bmpHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.drawColor(C