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);

您可以通过将所需的位移量与两个坐标相加来移动文本:

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 回答