• 好记性不如烂笔杆Android开发android绘制文本


    Canvas 作为绘制文本时,使用FontMetrics对象,计算位置的坐标。

    它的思路和java.awt.FontMetrics的基本相同。

    FontMetrics对象

    它以四个基本坐标为基准,分别为:

    ・FontMetrics.top
    ・FontMetrics.ascent
    ・FontMetrics.descent
    ・FontMetrics.bottom

    该图片将如下

    绘制文字的代码
     1 Paint textPaint = new Paint( Paint.ANTI_ALIAS_FLAG);
     2 textPaint.setTextSize( 35);
     3 textPaint.setColor( Color.WHITE);
     4 
     5 // FontMetrics对象
     6 FontMetrics fontMetrics = textPaint.getFontMetrics();
     7 
     8 String text = "abcdefghijklmnopqrstu";
     9 
    10 // 计算每一个坐标
    11 float baseX = 0;
    12 float baseY = 100;
    13 float topY = baseY + fontMetrics.top;
    14 float ascentY = baseY + fontMetrics.ascent;
    15 float descentY = baseY + fontMetrics.descent;
    16 float bottomY = baseY + fontMetrics.bottom;
    17 
    18 // 绘制文本
    19 canvas.drawText( text, baseX, baseY, textPaint);
    20 
    21 // BaseLine描画
    22 Paint baseLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);>
    23 baseLinePaint.setColor( Color.RED);
    24 canvas.drawLine(0, baseY, getWidth(), baseY, baseLinePaint);
    25 
    26 // Base描画
    27 canvas.drawCircle( baseX, baseY, 5, baseLinePaint);
    28 
    29 // TopLine描画
    30 Paint topLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
    31 topLinePaint.setColor( Color.LTGRAY);
    32 canvas.drawLine(0, topY, getWidth(), topY, topLinePaint);
    33 
    34 // AscentLine描画
    35 Paint ascentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
    36 ascentLinePaint.setColor( Color.GREEN);
    37 canvas.drawLine(0, ascentY, getWidth(), ascentY, ascentLinePaint);
    38 
    39 // DescentLine描画
    40 Paint descentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
    41 descentLinePaint.setColor( Color.YELLOW);
    42 canvas.drawLine(0, descentY, getWidth(), descentY, descentLinePaint);
    43 
    44 // ButtomLine描画
    45 Paint bottomLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
    46 bottomLinePaint.setColor( Color.MAGENTA);
    47 canvas.drawLine(0, bottomY, getWidth(), bottomY, bottomLinePaint);

    这个是从别处转载的,图片是精华,谢谢原作者!

  • 相关阅读:
    数字重排
    环游世界
    Hibernate笔记(一)增删改查CRUD
    Sliding Window Algorithm 滑动窗口算法
    纯HTML/CSS/JS实现淘宝、京东两种轮播图
    COA计算机组织与结构笔记
    数据结构与算法笔记:最小生成树Kruskal、Prim算法与JAVA实现
    数据结构与算法笔记:图的基础与JAVA实现
    数据结构与算法:并查集
    JDBC学习笔记
  • 原文地址:https://www.cnblogs.com/zjqlogs/p/2815678.html
Copyright © 2020-2023  润新知