【问题标题】:Android canvas drawText y-position of textAndroid canvas drawText 文本的y位置
【发布时间】:2012-05-23 07:11:39
【问题描述】:

我正在使用 Canvas 创建一个带有一些背景和一些文本的 Drawable。可绘制对象用作 EditText 内的复合可绘制对象。

文本是通过画布上的 drawText() 绘制的,但在某些情况下,绘制文本的 y 位置确实存在问题。在这种情况下,部分字符会被截断(参见图片链接)。

没有定位问题的字符:

http://i50.tinypic.com/zkpu1l.jpg

有定位问题的字符,文本包含“g”、“j”、“q”等:

http://i45.tinypic.com/vrqxja.jpg

您可以找到代码 sn-p 来重现以下问题。

有专家知道如何确定 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();
   }
}

【问题讨论】:

    标签: android text canvas position drawtext


    【解决方案1】:

    我认为假设 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);是解决方案
    • @darksaga 你为什么不把这个作为答案发布。
    【解决方案2】:

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

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

    我在this answer 中详细阐述了这个主题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多