After looking through the source code slightly, I found the public parameters like baselineShift
is actually NOT applied to the canvas when you invoke drawText
using the textPaint as parameter but an extra data the TextPaint
save for you to retrieve to manually apply to the drawing action.
For example, I want (0, 0) to be the center position of the text I draw, and that's how I usually did.
Example
private val mTextPaint = TextPaint().apply {
color = Colors.BLACK
textSize = 14.sp
isAntiAlias = true
baselineShift = (textSize / 2 - descent()).toInt()
textAlign = Paint.Align.CENTER
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawText("Hello World", 0f, mTextPaint.baselineShift.toFloat(), mTextPaint)
}
Note: sp
is an extension property in kotlin, which works like the function sp2px(Number sp)
And the (textSize / 2 - descent()).toInt()
may not be the most accurate approach to center the text verically, please leave a comment if you have any better approach.