2013-10-17 40 views
2

編輯:從仿真器的問題就來了,錯誤並沒有出現真正的設備:(Paint.getTextBounds()返回到大高度

我試圖繪製自定義視圖一些文字上並且必須在那裏測量它,但Paint.getTextBounds()的值返回的高度比實際文本高出約30%,這使得所有內容都變得古怪。

我發現這個:Android Paint: .measureText() vs .getTextBounds()並嘗試添加解決方案代碼給我自己的onDraw,看到我的測量錯誤與我的代碼相同。下面是結果圖片: enter image description here

比較用: enter image description here 的圖像被複制從Android Paint: .measureText() vs .getTextBounds()

注意的間距在所述第一圖像中的文本的上方。任何想法可能會造成這種情況?或者是否有其他方法來測量拉線的高度?

這裏是的onDraw方法:

@Override 
public void onDraw(Canvas canvas){ 
//  canvas.drawColor(color_Z1); 
//  r.set(0, 0, (int)(width*progress), height); 
//  paint.setColor(color_Z2); 
////  canvas.drawRect(r, paint); 
//  textPaint.getTextBounds(text, 0, text.length(), r); 
//  canvas.drawRect(r, paint); 
//  canvas.drawText(text, 0, r.height(), textPaint); 

    final String s = "Hello. I'm some text!"; 

    Paint p = new Paint(); 
    Rect bounds = new Rect(); 
    p.setTextSize(60); 

    p.getTextBounds(s, 0, s.length(), bounds); 
    float mt = p.measureText(s); 
    int bw = bounds.width(); 

    Log.i("LCG", String.format(
      "measureText %f, getTextBounds %d (%s)", 
      mt, 
      bw, bounds.toShortString()) 
    ); 
    bounds.offset(0, -bounds.top); 
    p.setStyle(Style.STROKE); 
    canvas.drawColor(0xff000080); 
    p.setColor(0xffff0000); 
    canvas.drawRect(bounds, p); 
    p.setColor(0xff00ff00); 
    canvas.drawText(s, 0, bounds.bottom, p); 
} 
+0

您是否試圖在頂部繪製文字?爲什麼不在頂部座標繪製,並通過文本高度來補償繪製高度。沒有修改邊界。 – Doomsknight

+0

是的,這段代碼應該沿着頂部排列問題是,getTextBounds返回紅色矩形whos高度更大hte文本,所以我沒有hte文本的真正高度... – SverkerSbrg

+0

我認爲它與字體。你的應用程序(Roboto)和原來的SO問題(Droid Sans,我假設)是不同的。嘗試使用沒有任何特殊字符的文本示例。例如,「abcdefghijklmnopqrstuvwxyz」。 – Delyan

回答

0

我因此未測試的代碼,但我沒有看到有Paint.getTextBounds)的任何問題(:

public class TextBoundsTest extends View { 
    private Paint paint; 
    private Rect bounds; 

    public TextBoundsTest(Context context) { 
     super(context); 
     paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     paint.setTextSize(32); 
     bounds = new Rect(); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     String text = "this is my text"; 
     paint.getTextBounds(text, 0, text.length(), bounds); 
     Log.d(TAG, "onDraw " + bounds); 

     int x = (getWidth() - bounds.width())/2; 
     int y = 70; 

     paint.setColor(0xff008800); 
     bounds.offset(x, y); 
     canvas.drawRect(bounds, paint); 

     paint.setColor(0xffeeeeee); 
     canvas.drawText(text, x, y, paint); 
    } 
} 

在Activity.onCreate補充一點:

TextBoundsTest view = new TextBoundsTest(this); 
setContentView(view); 

結果是: enter image description here

+0

問題是getTextBounds方法返回紅色矩形,與我鏈接的解決方案中的矩形比較,它們不同。所以我錯過了正確的文字高度測量。 – SverkerSbrg

+0

我不理解你,運行我的代碼,看到一個綠色的矩形完全匹配給定的文字 – pskink

+0

你改變了什麼嗎?您發佈的圖片看起來不像我的結果 – pskink