javaandroidandroid-imageviewandroid-canvasandroid-paint

How to get a reference to the top and the bottom of a canvas for dynamic positioning?


I have 2 TextViews on top of an ImageView. I am using the Canvas and Paint classes to draw the captions on the picture. I want the captions to have about 20dp of gap between the top of the image and the top of the TextView. What are some ways to get these values to input into the y value of Canvas.drawText()?


Solution

  • The text origin is like the image, it starts on left top, for the top text just set the y origin to +20dp, for the bottom text set the y origin to text.height+20dp

    Center text:

    x = image.width/2 - text.width/2;
    

    Top text Y axis

    y = 20;
    

    Bottom text Y axis:

    y = image.height - 20 - text.height;
    

    Is important that you measure the text before attempting yo get the width of the drawed text.

    Check this answer: Measuring text height to be drawn on Canvas ( Android )