美文网首页
自定义View -- 绘制文字

自定义View -- 绘制文字

作者: Passon_Fang | 来源:发表于2016-12-26 21:02 被阅读110次

title: 自定义View -- 绘制文字
date: 2016-03-30 09:23:14
tags: [View, 自定义View, 文字]
categories: Android


绘制文字

方法一 常用

public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint)
  • 参数1: 需要绘制的文本
  • 参数2: 绘制的文本起始 x 坐标
  • 参数3: 绘制的文本起始 y 坐标

获取文字的宽度

方式一:

    /**
     * @param text  绘制的文字
     * @param paint 画笔
     * @return 文字的宽度
     */
    public int getTextWidth(String text, Paint paint) {
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.left + bounds.width();
        return width;
    }

方式二:

    /**
     * @param text  绘制的文字
     * @param paint 画笔
     * @return 文字的宽度
     */
    public int getTextWidth2(String text, Paint paint) {
        return ((int) paint.measureText(text));
    }

获取文字的高度

    /**
     * @param text  绘制的文字
     * @param paint 画笔
     * @return 文字的高度
     */
    public int getTextHeight(String text, Paint paint) {
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int height = bounds.bottom + bounds.height();
        return height;
    }

文字的度量,参数获取 Paint.FontMetrics

    mPaint.setStyle(Paint.Style.STROKE);
    canvas.drawRect(100, 100, 700, 300, mPaint);
    mPaint.setTextSize(100);    // 必须设置大小才能得到五条线的值
    Paint.FontMetrics metrics = mPaint.getFontMetrics(); // 基线
    float top = metrics.top;
    float ascent = metrics.ascent; // 五条线
    float leading = metrics.leading;
    float descent = metrics.descent;
    float bottom = metrics.bottom; // 最低底边的线
    Log.d(TAG, "top=" + top + "ascent=" + ascent + "leading=" + leading + "descent=" + descent + "bottom=" + bottom);
    canvas.drawText("测试文字", 100, 300, mPaint);  // 文字的基线 baseline    top,ascent,leading,descent,bottom

文本绘制水平居中

        float x = (getWidth() - paint.measureText(text))/2
        # x

文本垂直居中

        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        float y = getHeight() / 2 + (Math.abs(fontMetrics.ascent) - fontMetrics.descent) / 2;

        # y

Paint 中和绘制文本相关的方法

  • mTextPaint.setStrikeThruText(true); :设置文本删除线
  • setTextSize(float f)
  • setUnderlineText(booelan b): 设置下滑线

相关文章

网友评论

      本文标题:自定义View -- 绘制文字

      本文链接:https://www.haomeiwen.com/subject/vuqsvttx.html