Android canvas drawText文本的y位置

dar*_*aga 27 android text position canvas drawtext

我正在使用Canvas创建一个带有一些背景和一些文本的Drawable.drawable用作EditText内的复合drawable.

文本是通过画布上的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();
   }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 26

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

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

如果textBounds是从+5到-5,并且您在y = height(10)处绘制文本,那么您将只看到文本的上半部分.

  • 谢谢你指点我正确的方向.canvas.drawText(text,0,textBounds.height() - textBounds.bottom,paint); 是解决方案 (13认同)

dam*_*911 13

我相信如果你想在左上角附近画文字你应该这样做:

canvas.drawText(text, -textBounds.left, -textBounds.top, paint);
Run Code Online (Sandbox Code Playgroud)

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

canvas.drawText(text, -textBounds.left + yourX, -textBounds.top + yourY, paint);
Run Code Online (Sandbox Code Playgroud)

这个(至少对我而言)的原因是getTextBounds()告诉你drawText()在x = 0和y = 0的情况下绘制文本的位置.所以你必须通过减去Android中处理文本的方式引入的位移(textBounds.left和textBounds.top)来抵消这种行为.

这个答案中,我详细阐述了这个主题.