【问题标题】:Get the text height including the font size and set that height获取包括字体大小在内的文本高度并设置该高度
【发布时间】:2012-12-25 23:16:44
【问题描述】:

我有一个名为 Hello 的文本,现在我需要为这个应用字体大小,比如 12 或 18,一旦我们将字体应用于文本,文本大小就会增加。

所以现在我需要使用paint来获取包括字体大小在内的文本高度。

我尝试过绘制以下内容:

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();
// Measure the text rectangle to get the height
paint.getTextBounds(finalVal, 0, finalVal.length(), result);

但它不起作用,请帮助

编辑

我正在尝试根据 textheight 动态设置 webview 的高度,我正在获取单行的文本高度,例如 "Hello" 但如果文本中有两行 "My name is abc and my dads name is xyz and my moms name is 123" now its not getting the proper text height".

【问题讨论】:

  • 究竟是什么不起作用?
  • 嗯...听起来很奇怪。为什么需要这样做?
  • @Goofy 我发布了解决方案,它对我有用。

标签: android android-webview paint


【解决方案1】:

试试这个方法:

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

这是输出:

WIDTH        : 40
HEIGHT       : 14

如果我设置这个,

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

我的输出是:

WIDTH        : 559
HEIGHT       : 18

【讨论】:

  • 谢谢你的答案,我以前做过这个,我也得到了相同的答案,但我们根据设备的高度和宽度来设置它,你可以看到你好这个词和多行高度没有差别很大
【解决方案2】:

您可以从FontMetrics 获取文本高度。无论当前的文本字符串是什么,它对于特定的字体和字体大小都是恒定的。

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

查看我更完整的答案here。我在那个答案中比较了getTextBoundsFontMetrics

【讨论】:

  • 尝试在父画布中居中时不起作用。所以,不是。唯一接近的值是FontMetrics#bottom
【解决方案3】:

paint.setTextSize(18);这一行告诉了文本的高度

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2018-08-05
    • 2012-12-28
    相关资源
    最近更新 更多