30

Canvasを使用して、背景とテキストを含むDrawableを作成しています。ドローアブルは、EditText内の複合ドローアブルとして使用されます。

テキストはキャンバス上で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();
   }
}
4

2 に答える 2

28

textBounds.bottom = 0と仮定するのはおそらく間違いだと思います。これらの降順の文字の場合、これらの文字の下部はおそらく0未満です(つまり、textBounds.bottom> 0)。あなたはおそらく次のようなものが欲しいでしょう:

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

textBoundsが+5から-5で、y = height(10)でテキストを描画する場合、テキストの上半分のみが表示されます。

于 2012-05-15T18:20:07.090 に答える
15

左上隅の近くにテキストを描画したい場合は、次のようにする必要があると思います。

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

また、必要な変位量を2つの座標に合計することで、テキスト内を移動できます。

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

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

この回答では、このトピックについてもう少し詳しく説明します。

于 2013-02-08T05:45:37.510 に答える