Paint.FontMetrics类简介

Google文档中的描述:
/**
* Class that describes the various各种 metrics指标 for a font at a given text size.
* Remember, Y values increase going down, so those values will be positive正数,
* and values that measure distances距离 going up will be negative负数. This class
* is returned by getFontMetrics().
*/
public static class FontMetrics {
//The maximum distance above the baseline for the tallest glyph in the font at a given text size.
public float top;
//【字符顶部】The recommended推荐的 distance above the baseline for singled spaced text.
public float ascent;
//【字符底部】The recommended distance below the baseline for singled spaced text.
public float descent;
//The maximum distance below the baseline for the lowest glyph in the font at a given text size.
public float bottom;
//【字符行间距】The recommended additional额外的 space to add between lines两行之间 of text.
public float leading;
}

网上找的各种模型图

注意Y坐标基准点是在BaseLine那个位置,而非AscentLine或Top那个位置

Paint的ascent和descent方法--算高度

这两个是native方法
//Return the distance above (negative) the baseline (ascent) based on the current typeface字体 and text size.
public native float ascent();
//Return the distance below (positive) the baseline (descent) based on the current typeface and text size.
public native float descent();
可以通过 mPaint.ascent()+ mPaint.descent() 获取文字高度

Paint的measureText方法--获取宽度

/**
* Return the width of the text.
*
* @param text The text to measure. Cannot be null.
* @param start The index of the first character to start measuring
* @param end 1 beyond the index of the last character to measure
* @return The width of the text
*/
public float measureText(String text, int start, int end) {
if (text == null) throw new IllegalArgumentException("text cannot be null");
if ((start | end | (end - start) | (text.length() - end)) < 0) throw new IndexOutOfBoundsException();
if (text.length() == 0 || start == end) return 0f;
if (!mHasCompatScaling) return (float) Math.ceil(native_measureText(text, start, end, mBidiFlags));

final float oldSize = getTextSize();
setTextSize(oldSize*mCompatScaling);
float w = native_measureText(text, start, end, mBidiFlags);
setTextSize(oldSize);
return (float) Math.ceil(w*mInvCompatScaling);
}
通过这个方法即可以轻松的获取到文字的的宽度

Paint的getTextBounds方法--获取边界

/**
* Return in bounds (allocated by the caller 由调用者分配) the smallest最小的 rectangle that
* encloses围起来 all of the characters, with an implied origin默认的起始位置 at (0,0).
* @param text String to measure and return its bounds
* @param start Index of the first char in the string to measure
* @param end 1 past the last char in the string measure
* @param bounds Returns the unioned bounds of all the text. Must be allocated by the caller.
*/
public void getTextBounds(String text, int start, int end, Rect bounds) {
if ((start | end | (end - start) | (text.length() - end)) < 0) throw new IndexOutOfBoundsException();
if (bounds == null) throw new NullPointerException("need bounds Rect");
nativeGetStringBounds(mNativePaint, mNativeTypeface, text, start, end, mBidiFlags, bounds);
}
这个方法需要提供一个参数 Rect 矩形区域,这个方法将文字的区域传递到 Rect

Paint的获取

比如对于TextView,要通过TextView的getPaint()得到Paint,而不能new一个或者拿其他不相干的Paint
/**
* @return the base paint used for the text. Please use this only to
* consult查阅 the Paint's properties属性 and not to change them.
*/
public TextPaint getPaint() {
return mTextPaint;
}
如果是在自定义View 中,则可以直接通过Paint调用相关方法去获取文字的宽高等信息

测试代码

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String text = "aA bB fF gG";
        TextView tv_info = new TextView(this);
        tv_info.setTextColor(Color.BLUE);
        tv_info.setBackgroundColor(0x5500ff00);
        tv_info.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        tv_info.setText(text);
        setContentView(tv_info);
        tv_info.measure(0, 0);//必须手动调用测量方法,否则getMeasuredHeight获取不到值。另外,即使测量过了getHeight也获取不到值
        Paint mPaint = tv_info.getPaint();
        Log.i("bqt", "ascent()的值为" + mPaint.ascent() + ",descent()的值为" + mPaint.descent());//-33.398438, 8.7890625
        Log.i("bqt", "字符的高度为" + (-mPaint.ascent() + mPaint.descent()) + ",字符的长度为" + mPaint.measureText(text));//42.1875,190.0
        Log.i("bqt", "测量的高度为" + tv_info.getMeasuredHeight() + ",测量的宽度为" + tv_info.getMeasuredWidth());//49,190
        Rect mRect = new Rect();
        mPaint.getTextBounds(text, 0, text.length(), mRect);
        Log.i("bqt", "字符的边界为" + mRect.left + "," + mRect.top + "," + mRect.right + "," + mRect.bottom);//1,-28,187,8
        Log.i("bqt", "字符的高度为" + (mRect.bottom - mRect.top) + ",字符的长度为" + (mRect.right - mRect.left));//36,186
    }

}

文字尺寸、宽高的测量 Paint FontMetrics的更多相关文章

  1. frame方式布局一段文子,设置宽高

    计算一段文字的宽高 /** * 计算一段文字的宽高 * * @param size 这段文字的最大宽高 * @param options NSStringDrawingUsesLineFragment ...

  2. iOS_根据文字字数动态确定Label宽高

    iOS7中用以下方法 CGSize 替代过时的iOS6中的- (CGSize)sizeWithFont:(UIFont *)font 方法 // iOS7_API_根据文字 字数动态确定Label宽高 ...

  3. iOS根据文字字数动态确定Label宽高

    我们有时候在写项目的时候,会碰到,意见反馈,还有其他地方,讲座活动细则等需要大篇展示的文本, 因为每次服务器返回的内容大小不一,所以需要动态的调整label的宽高: 在ios 6 的时候可以: -(v ...

  4. iOS 根据文字字数动态确定Label宽高

    iOS7中用以下方法 - (CGSize)sizeWithAttributes:(NSDictionary *)attrs; 替代过时的iOS6中的- (CGSize)sizeWithFont:(UI ...

  5. 微信 小程序 drawImage wx.canvasToTempFilePath wx.saveFile 获取设备宽高 尺寸问题

    以下问题测试环境为微信开发者0.10.102800,手机端iphone6,如有不对敬谢指出. 根据我的测试,context.drawImage,在开发者工具中并不能画出来,只有预览到手机中显示. wx ...

  6. 如何设置a标签的宽高,如何使a标签的文字垂直居中

    通常情况下a标签是没有宽高的,设置 width 和 height 没有作用. 若要使用 width 和 height,需要把a标签转为块级元素,即:display:block|inline-block ...

  7. js判断图片上传时的文件大小,和宽高尺寸

    今天在做图片上传的小功能,使用了一个kissy上传组件.很好奇它是如何在图片上传前,检测到图片的大小和尺寸的?我们来写个小实例实现一下吧 如何读取图片的size 首先,原生input file控件有个 ...

  8. iOS 让UIButton根据文字内容自动计算宽高

    Xcode自带的UIButton控件是没有办法根据文字内容计算自身的宽和高的,下面演示一下问题, 我用代码方式创建一个UIButton,并且设置了一些属性,下面看一下效果图 一切都是这么的美好,跟我们 ...

  9. 不定宽高的文字在div中垂直居中

    本人在面试的时候被问到:如何使一段不定宽高的文字垂直居中呢? 现在来总结一下: 在body中写入结构 <div id="main">    <div id=&qu ...

随机推荐

  1. pyqt5之QColorDialog颜色对话框最简单使用

           设置窗体背景颜色 QWidget.setStyleSheet('QWidget {background-color:#88ab45}') 颜色对话框取得颜色值是十六进制. col=QCo ...

  2. cpp笔记(长期更新)

    c++0x:c++11标准成为正式标准之前的草案临时名字 多态:接口的多种不同的实现方式即为多态,即子类类型的指针赋值给父类类型的指针 动态内存(堆)的管理是通过一对运算符来完成的: new:在动态内 ...

  3. 转:The Great DOM Fuzz-off of 2017

    The Great DOM Fuzz-off of 2017 Posted by Ivan Fratric, Project Zero https://googleprojectzero.blogsp ...

  4. Python类总结-析构函数和__call__方法

    class Foo: def __init__(self): pass #析构函数 def __del__(self): print('解释器要销毁我了,我要做最后一次呐喊') def __call_ ...

  5. HDU4893【线段树单点、区间更新】

    题目链接[http://acm.hdu.edu.cn/showproblem.php?pid=4893] 题意:输入n.q.表示有n个数,初始化默认这n个数都为零,有q次操作,操作种类分为三种:1.输 ...

  6. 51nod 1962区间计数(单调栈加二分)

    题目要求是求出两个序列中处于相同位置区间并且最大值相同的区间个数,我们最直观的感受就是求出每个区间的最大值,这个可以O(N)的求,利用单调栈求出每个数作为最大值能够覆盖的区间. 然后我们可以在进行单调 ...

  7. UOJ #30. [CF Round #278] Tourists

    UOJ #30. [CF Round #278] Tourists 题目大意 : 有一张 \(n\) 个点, \(m\) 条边的无向图,每一个点有一个点权 \(a_i\) ,你需要支持两种操作,第一种 ...

  8. luoguP3255 [JLOI2013]地形生成 动态规划

    出题人语文真好... 各不相同的标号和高度 = 各不相同的标号 + 单独的高度... 第一问比较简单,考虑从大到小插入,在相同情况下,按关键值从小到大插入 这样子,关键大的元素一定会影响到关键小的元素 ...

  9. loj2480 [CEOI2017]One-Way Streets 边双+树上差分

    边双无法确定 缩完边双就是一棵树 树上差分随意弄一下吧... #include <vector> #include <cstdio> #include <cstring& ...

  10. JavaScript设计模式与开发实践——读书笔记1.高阶函数(上)

    说来惭愧,4个多月未更新了.4月份以后就开始忙起来了,论文.毕设.毕业旅行等七七八八的事情占据了很多时间,毕业之后开始忙碌的工作,这期间一直想写博客,但是一直没能静下心写.这段时间在看<Java ...