Kotlin实现58mm热敏打印机打印Bitmap无法居中对齐问题求助
解决方法
你的问题核心是生成Bitmap时,布局内容默认从画布左上角(0,0)开始绘制,没有计算居中需要的左侧偏移量,按以下步骤修改即可:
- 先确认你所用58mm热敏打印机的标准可打印像素宽度,市面绝大多数58mm热敏打印机的可打印宽度为
384px,你可以根据打印机手册调整该值。 - 计算布局内容的居中水平偏移量,绘制布局时将画布平移到偏移位置再绘制即可。
修改后的代码如下:
// 第一步:确认打印机可打印宽度,单位为像素 val printerAvailableWidth = 384 // 58mm打印机通用值,可根据实际型号调整 val h = binding.printLayout.getChildAt(0).height // 这里创建的Bitmap宽度用打印机可打印宽度,高度和原来一致 bitmap = Bitmap.createBitmap(printerAvailableWidth, h, Bitmap.Config.ARGB_8888) val c = Canvas(bitmap) // 测量布局时还是用布局自身的宽度参数,不要直接用打印宽度,避免布局被拉伸 val layoutNeedWidth = resources.getDimension(R.dimen.test_58mm).toInt() val sizeSpecWidth: Int = View.MeasureSpec.makeMeasureSpec(layoutNeedWidth, View.MeasureSpec.EXACTLY) val sizeSpecHeight: Int = View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY) printLayoutBinding.root.measure(sizeSpecWidth, sizeSpecHeight) val layoutMeasuredWidth: Int = printLayoutBinding.root.measuredWidth val layoutMeasuredHeight: Int = printLayoutBinding.root.measuredHeight // 计算居中需要的左侧偏移量,如果布局宽度超过打印宽度,这里偏移量为0避免内容越界 val offsetX = Math.max(0, (printerAvailableWidth - layoutMeasuredWidth) / 2) // 布局位置从偏移量开始,而不是从0开始 printLayoutBinding.root.layout(offsetX, 0, offsetX + layoutMeasuredWidth, layoutMeasuredHeight) printLayoutBinding.root.draw(c)
注意事项
- 如果你的布局实际宽度和打印机可打印宽度一致,那需要检查布局XML文件,确保布局内部的内容已经配置了居中属性。
- 如果你使用的是第三方打印SDK,可优先检查SDK是否提供了位图居中打印的API,直接调用API实现更简单。
- 如果打印机支持自定义位图打印起始X坐标,也可以在发送打印指令时直接设置X偏移量,不需要修改Bitmap生成逻辑,两种方案二选一即可。
内容的提问来源于stack exchange,提问作者Tanveer Hasan
相关产品推荐
相关产品推荐

