Android canvas drawText y-position of text

こ雲淡風輕ζ 提交于 2019-12-03 04:25:48
Tim

I think it's probably a mistake to assume that textBounds.bottom = 0. For those descending characters, the bottom parts of those characters are probably below 0 (which means textBounds.bottom > 0). You probably want something like:

canvas.drawText(text, 0, textBounds.top, paint); //instead of textBounds.height()

If your textBounds is from +5 to -5, and you draw text at y=height (10), then you'll only see the top half of the text.

damix911

I believe that if you want to draw text near the upper left corner you should do this:

canvas.drawText(text, -textBounds.left, -textBounds.top, paint);

And you can move around the text by summing the desired amount of displacement to the two coordinates:

canvas.drawText(text, -textBounds.left + yourX, -textBounds.top + yourY, paint);

The reason why this works (at least for me) is that getTextBounds() tells you where drawText() would draw the text in the event that x=0 and y=0. So you have to counteract this behavior by subtracting the displacement (textBounds.left and textBounds.top) introduced by the way text is handled in Android.

In this answer I elaborate a little more on this topic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!