我目前正在渲染位图,然后想将其发送到移动打印机。然而,我无法测量文本的高度,以便适当地提高y位置。
我的基本位图/画布/绘画配置如下(字体大小为16,位图尺寸为200x400(宽x高):
public MyRenderer() {
// Initialize bitmap
bitmap = Bitmap.createBitmap(200, 400, Bitmap.Config.ARGB_8888);
// Initialize canvas
canvas = new Canvas(bitmap);
// Initialize brush (Paint instance)
brush = new Paint();
brush.setTextSize(16);
brush.setTypeface(Typeface.SANS_SERIF);
brush.setColor(Color.BLACK);
brush.setStyle(Paint.Style.FILL);
brush.setAntiAlias(true);
brush.setTextAlign(Align.LEFT);
}
到目前为止一切都很好,现在我想做的是:如果我使用Paint的drawText方法,我需要提供x和y坐标。对于x来说,它是零(假设文本左对齐),但是对于y来说,我必须计算我打印的每个文本的高度并将其相加,以便我可以跟踪我的当前y位置。
这就是奇怪的地方:我正在使用以下方法确定文本的高度(使用之前初始化的Paint对象 - 它被称为“brush”):
public int measureHeight(String text) {
Rect result = new Rect();
// Measure the text rectangle to get the height
brush.getTextBounds(text, 0, text.length(), result);
return result.height();
}
上述方法对以下文本返回以下值:
1. "Hello World" 返回高度为12 2. "A camera instance can be used to compute 3D transformations and generate a matrix." 返回高度为16 3. "Introducing Android Design: The place to learn about principles, building blocks, and patterns for creating world-class Android user interfaces. Whether you're a UI professional or a developer playing that role, these docs show you how to make good design decisions, big and small." 返回高度为16 我理解第二和第三个的高度比第一个大,但如果一行的高度为12(如第一个),那么多行的高度为16就没有意义了吗?
我错过了什么吗?有一个方便的方法可以测量文本的宽度(使用paint实例并调用measureText("myText")),这个方法非常完美,但是当涉及到高度时,我感到困惑,因为上面给出的结果对我来说毫无意义。
编辑
我知道getTextBounds可能不会自动换行多行文本,这没关系,我已经编写了一个拆分文本的方法,但即使它只测量一行,上述长度值仍然似乎不太可能。