2012-05-15 29 views
25

キャンバスを使用して、背景とテキストを含むDrawableを作成しています。ドロウアブルは、EditText内の複合ドロウアブルとして使用されます。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

私はそれが(0 textBounds.bottomを意味>)textBounds.bottom = 0これらの降順の文字については、それらの文字の下の部分は、おそらく0以下であると仮定することはおそらく間違いだと思います。

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

あなたtextBoundsが+5から-5であり、そしてあなたは、Y =高さ(10)でテキストを描画した場合、その後、あなたがテキストの上半分のみ表示されます:あなたは、おそらくのような何かをしたいです。

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

そして、あなたは2点の座標に変位の所望の量を合計することで、テキストの周りに移動することができます:

+13

私は正しい方向に向いてくれてありがとう。 canvas.drawText(text、0、textBounds.height() - textBounds.bottom、paint);解決策だった – darksaga

10

は、私はあなたが左上隅の近くにテキストを描画したい場合には、これを行うべきであると信じている

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

これは(少なくとも私にとっては)getTextBounds()が、x = 0、y = 0というイベントでdrawText()がテキストを描画する場所を示している理由です。したがって、Androidでテキストが処理される方法で導入された変位(textBounds.leftとtextBounds.top)を差し引くことで、この動作を打ち消す必要があります。

this answerこのトピックについてもう少し詳しく説明します。

関連する問題