Get the text height including the font size and set that height

后端 未结 3 1302
遥遥无期
遥遥无期 2021-01-02 22:37

i have a text called Hello now i need to apply fontsize for this say 12 or 18 now as soon as we apply font to the text the text size increases.

so now i

相关标签:
3条回答
  • 2021-01-02 22:56

    paint.setTextSize(18); this line tells the hight of text

    0 讨论(0)
  • 2021-01-02 22:59

    You can get the text height from the FontMetrics. It is constant for a particular font and font size, no matter what the current text string is.

    Paint.FontMetrics fm = mTextPaint.getFontMetrics();
    float textHeight = fm.descent - fm.ascent;
    float lineHeight = fm.bottom - fm.top + fm.leading;
    

    See my fuller answer here. I compare getTextBounds with FontMetrics in that answer.

    0 讨论(0)
  • 2021-01-02 23:14

    Try this way:

    String finalVal ="Hello";
    
    Paint paint = new Paint();
    paint.setTextSize(18);
    paint.setTypeface(Typeface.SANS_SERIF);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.FILL);
    
    Rect result = new Rect();
    paint.getTextBounds(finalVal, 0, finalVal.length(), result);
    
    Log.d("WIDTH        :", String.valueOf(result.width()));
    Log.d("HEIGHT       :", String.valueOf(result.height()));
    

    Here is the output:

    WIDTH        : 40
    HEIGHT       : 14
    

    If I set this,

    String finalVal ="My name is abc and my dads name is xyz and my moms name is 123";
    

    My Output is :

    WIDTH        : 559
    HEIGHT       : 18
    
    0 讨论(0)
提交回复
热议问题