Android-使用静态布局在位图的底部绘制文本

时间:2018-08-25 04:13:17

标签: android text bitmap android-bitmap staticlayout

我有以下代码将一些文本放在图像的顶部:

    val paint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    paint.color = Color.WHITE
    paint.textSize = 40f //* context.resources.displayMetrics.density
    paint.typeface = Typeface.DEFAULT_BOLD
    //paint.textAlign = Paint.Align.
    paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY)

    val teststr = "Hello World Hello World Hello World Hello World"

    val canvas = Canvas(bitmap)
    val textLayout = StaticLayout(teststr, paint, canvas.width ,Layout.Alignment.ALIGN_CENTER, 1f, 0f, false)
    textLayout.draw(canvas)

但是,实际上,我希望文本位于图像的底部。如何将StaticLayoutBitmap的底部对齐,使文本显示在图像的底部。

Screenshot

1 个答案:

答案 0 :(得分:2)

事实证明这是正确的答案。从画布的高度中减去StaticLayout的高度。

    val paint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    paint.color = Color.WHITE
    paint.textSize = 40f //* context.resources.displayMetrics.density
    paint.typeface = Typeface.DEFAULT_BOLD
    //paint.textAlign = Paint.Align.
    paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY)

    val teststr = "Hello World"

    val canvas = Canvas(bitmap)

    val textLayout = StaticLayout(teststr, paint, canvas.width ,Layout.Alignment.ALIGN_CENTER, 1f, 0f, false)
    canvas.save()
    canvas.translate(0f,canvas.height - textLayout.height - 0.0f)
    textLayout.draw(canvas)
    canvas.restore()