androidtextbitmapandroid-bitmapstaticlayout

Android - Draw Text At The Bottom Of A Bitmap Using Static Layout


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


Solution

  • 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()