1

I have the following code that puts some text at the top of an image:

    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)

However, in reality, I want the text to be at the bottom of the image. How can I align the StaticLayout with the bottom of the Bitmap, so the text appears at the bottom of the image.

Screenshot

Foobar
  • 7,458
  • 16
  • 81
  • 161

1 Answers1

3

This turned out to be the correct answer. Subtract the height of the StaticLayout from the height of the canvas.

    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()
Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Hi!, It's an excellent answer but just facing an issue of margin/padding between image and text. How I can give some space between image and Text without clipping, Thanks in advance. – Monir Zzaman Jun 30 '20 at 12:20