1. 程式人生 > >計算出當前繪製出來的字串寬度和高度

計算出當前繪製出來的字串寬度和高度

寬度:

方法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程式碼  收藏程式碼
  1. Paint textPaint = new Paint( Paint.ANTI_ALIAS_FLAG);  
  2. textPaint.setTextSize( 35);  
  3. textPaint.setColor( Color.WHITE);  
  4. // FontMetrics物件  
  5. FontMetrics fontMetrics = textPaint.getFontMetrics();  
  6. String text = "abcdefghijklmnopqrstu";  
  7. // 計算每一個座標  
  8. float baseX = 0;  
  9. float baseY = 100;  
  10. float topY = baseY + fontMetrics.top;  
  11. float ascentY = baseY + fontMetrics.ascent;  
  12. float descentY = baseY + fontMetrics.descent;  
  13. float bottomY = baseY + fontMetrics.bottom;  
  14. // 繪製文字  
  15. canvas.drawText( text, baseX, baseY, textPaint);  
  16. // BaseLine描畫  
  17. Paint baseLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);>  
  18. baseLinePaint.setColor( Color.RED);  
  19. canvas.drawLine(0, baseY, getWidth(), baseY, baseLinePaint);  
  20. // Base描畫  
  21. canvas.drawCircle( baseX, baseY, 5, baseLinePaint);  
  22. // TopLine描畫  
  23. Paint topLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);  
  24. topLinePaint.setColor( Color.LTGRAY);  
  25. canvas.drawLine(0, topY, getWidth(), topY, topLinePaint);  
  26. // AscentLine描畫  
  27. Paint ascentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);  
  28. ascentLinePaint.setColor( Color.GREEN);  
  29. canvas.drawLine(0, ascentY, getWidth(), ascentY, ascentLinePaint);  
  30. // DescentLine描畫  
  31. Paint descentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);  
  32. descentLinePaint.setColor( Color.YELLOW);  
  33. canvas.drawLine(0, descentY, getWidth(), descentY, descentLinePaint);  
  34. // ButtomLine描畫  
  35. Paint bottomLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);  
  36. bottomLinePaint.setColor( Color.MAGENTA);  
  37. canvas.drawLine(0, bottomY, getWidth(), bottomY, bottomLinePaint);