計算出當前繪製出來的字串寬度和高度
阿新 • • 發佈:2019-02-13
寬度:
方法1:Paint paint= new Paint();
Rect rect = new Rect();
//返回包圍整個字串的最小的一個Rect區域
paint.getTextBounds(str, 0, 1, rect);
strwid = rect.width();
strhei = rect.height();
方法2:
//直接返回引數字串所佔用的寬度
strwid = paint.measureText(str);
高度:
strhgt = paint.getFontMetrics().descent- paint.getFontMetrics().ascent;
FontMetrics介紹
Canvas 作為繪製文字時,使用FontMetrics物件,計算位置的座標。
它的思路和java.awt.FontMetrics的基本相同。
FontMetrics物件
它以四個基本座標為基準,分別為:
・FontMetrics.top
・FontMetrics.ascent
・FontMetrics.descent
・FontMetrics.bottom
該圖片將如下
Java程式碼
- Paint textPaint = new Paint( Paint.ANTI_ALIAS_FLAG);
-
textPaint.setTextSize( 35);
- textPaint.setColor( Color.WHITE);
- // FontMetrics物件
- FontMetrics fontMetrics = textPaint.getFontMetrics();
- String text = "abcdefghijklmnopqrstu";
- // 計算每一個座標
- float baseX = 0;
- float baseY = 100;
- float topY = baseY + fontMetrics.top;
- float ascentY = baseY + fontMetrics.ascent;
-
float descentY = baseY + fontMetrics.descent;
- float bottomY = baseY + fontMetrics.bottom;
- // 繪製文字
- canvas.drawText( text, baseX, baseY, textPaint);
- // BaseLine描畫
- Paint baseLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);>
- baseLinePaint.setColor( Color.RED);
- canvas.drawLine(0, baseY, getWidth(), baseY, baseLinePaint);
- // Base描畫
- canvas.drawCircle( baseX, baseY, 5, baseLinePaint);
- // TopLine描畫
- Paint topLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
- topLinePaint.setColor( Color.LTGRAY);
- canvas.drawLine(0, topY, getWidth(), topY, topLinePaint);
- // AscentLine描畫
- Paint ascentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
- ascentLinePaint.setColor( Color.GREEN);
- canvas.drawLine(0, ascentY, getWidth(), ascentY, ascentLinePaint);
- // DescentLine描畫
- Paint descentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
- descentLinePaint.setColor( Color.YELLOW);
- canvas.drawLine(0, descentY, getWidth(), descentY, descentLinePaint);
- // ButtomLine描畫
- Paint bottomLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
- bottomLinePaint.setColor( Color.MAGENTA);
- canvas.drawLine(0, bottomY, getWidth(), bottomY, bottomLinePaint);