Android画布drawText文本的y轴位置是什么?

31

我正在使用 Canvas 创建一个 Drawable,其中包含一些背景和文本。这个 Drawable 被用作 EditText 中的复合 Drawable。

文本是通过在 Canvas 上调用 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();
   }
}
2个回答

29

我认为假设textBounds.bottom = 0可能是错误的。对于那些下降字符,这些字符的底部部分可能在0以下(这意味着textBounds.bottom > 0)。你可能想要像这样的东西:

canvas.drawText(text, 0, textBounds.top, paint); //代替textBounds.height()

如果你的textBounds从+5到-5,并且你在y=height (10)处绘制文本,则只会看到文本的顶部一半。


13
感谢您为我指明了正确的方向。canvas.drawText(text, 0, textBounds.height()-textBounds.bottom, paint); 是解决方案。 - darksaga
@darksaga 为什么不把这个作为答案发布呢? - user9599745

16

我认为如果您想在左上角附近绘制文本,应该这样做:

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)来抵消这种行为。

这个答案中,我对这个话题进行了更详细的阐述。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接