牛骨文教育服务平台(让学习变的简单)
博文笔记

android 里面Canvas绘制文本的方法

创建时间:2015-09-02 投稿人: 浏览次数:1374

在做项目的时候总是会遇到一些要再图片上叠加文字的需求,这个问题的解决方式有很多种,通过布局来实现:一个ImageView和一个TextView堆放好就行,或者直接用button,background为图片,text就是我要放的的文字,这样也可以也,但是最近遇到了一个这些方式解决不了的问题:在使用FAB时要在图标上面添加数字,要说这个问题其实也是个简单的问题,解决的话就是通过Canvas在bitmap上面drawText就可以了,但是Canvas在drawText时,画上去的text不是我要的效果,一番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;
    }

FontMetrics是Paint的内部类

Canvas之drawText

Canvas类里面有很多drawText的重载函数
这里写图片描述
还有几个drawTextOnPath,drawTextRun函数,他们的具体实现都是调用的native函数具体实现不明,这些我也用不到.我要的是如何控制字体绘制.

第一张图片和FontMetrics相对应,FontMetrics是android对于字体的描述类,其中的参数在绘制文本时非常重要,具体参数的介绍上面也有,需要注意的是位于基准线(baseline)之上的top、ascent均为负值.

上面那么多的drawText函数,其实仔细看里面关于控制绘制文本位置的参数始终不变,两个float参数,一个是从x轴的何处开始绘制,另一个参数是绘制这一行文字的基准线(baseline)坐标,理解了最上面的图,我们就可以随心所欲的控制文本出现的地方

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。