2012-05-15 60 views
25

我正在使用Canvas創建一些帶有背景和文本的Drawable。 drawable用作EditText中的複合drawable。Android畫布drawText文本的y位置

該文本是通過畫布上的drawText()繪製的,但在某些情況下,我確實遇到了繪製文本的y位置問題。在這些情況下,部分字符的部分被切斷(見圖片鏈接)。

字符未經定位的問題:

http://i50.tinypic.com/zkpu1l.jpg

與定位的問題人物,文字中包含 'G', 'J', 'Q' 等:

http://i45.tinypic.com/vrqxja.jpg

你可以找到一個代碼片段來重現下面的問題。

是否有專家知道如何確定y位置的正確偏移量?

public void writeTestBitmap(String text, String fileName) { 
    // font size 
    float fontSize = new EditText(this.getContext()).getTextSize(); 
    fontSize+=fontSize*0.2f; 
    // paint to write text with 
    Paint paint = new Paint(); 
    paint.setStyle(Style.FILL); 
    paint.setColor(Color.DKGRAY); 
    paint.setAntiAlias(true); 
    paint.setTypeface(Typeface.SERIF); 
    paint.setTextSize((int)fontSize); 
    // min. rect of text 
    Rect textBounds = new Rect(); 
    paint.getTextBounds(text, 0, text.length(), textBounds); 
    // create bitmap for text 
    Bitmap bm = Bitmap.createBitmap(textBounds.width(), textBounds.height(), Bitmap.Config.ARGB_8888); 
    // canvas 
    Canvas canvas = new Canvas(bm); 
    canvas.drawARGB(255, 0, 255, 0);// for visualization 
    // y = ? 
    canvas.drawText(text, 0, textBounds.height(), paint); 

    try { 
     FileOutputStream out = new FileOutputStream(fileName); 
     bm.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

回答

25

我認爲它可能是一個錯誤的假設,textBounds.bottom = 0。對於那些降字符,這些字符的底部部分是可能低於0(這意味着textBounds.bottom> 0)。你可能想是這樣的:

canvas.drawText(text, 0, textBounds.top, paint); //instead of textBounds.height()

如果您textBounds是從+5到-5,和你畫在y =身高(10)文本,那麼您只能看到文字的上半部分。

+13

感謝您指點我正確的方向。 canvas.drawText(text,0,textBounds.height() - textBounds.bottom,paint);是解決方案 – darksaga

10

我相信,如果你想繪製文本靠近左上角,你應該這樣做:

canvas.drawText(text, -textBounds.left, -textBounds.top, paint); 

,您可以通過總結位移的所需量的兩個座標中的文本中移動:

canvas.drawText(text, -textBounds.left + yourX, -textBounds.top + yourY, paint); 

之所以這樣工作(至少對我來說)是getTextBounds()告訴你在哪裏的drawText()將利用在事件x = 0和Y = 0的文本。所以你必須通過減去Android中處理文本的方式引入的位移(textBounds.left和textBounds.top)來抵消這種行爲。

this answer我詳細說明了這個話題。