0

我在 ImageView 之上有 2 个 TextView。我正在使用CanvasPaint类在图片上绘制标题。我希望标题在图像顶部和 TextView 顶部之间有大约 20dp 的间隙。有什么方法可以让这些值输入到 的 y 值中Canvas.drawText()

4

2 回答 2

1

文本原点就像图像一样,从左上角开始,顶部文本只需将 y 原点设置为 +20dp,底部文本将 y 原点设置为 text.height+20dp

中心文字:

x = image.width/2 - text.width/2;

顶部文字 Y 轴

y = 20;

底部文字 Y 轴:

y = image.height - 20 - text.height;

在尝试获取绘制文本的宽度之前测量文本很重要。

检查这个答案: 测量要在画布上绘制的文本高度(Android)

于 2019-02-27T02:40:52.553 回答
0

您可以点击此链接https://developer.android.com/training/custom-views/custom-drawing#java。它包含定位的详细描述。在你的情况下,

你需要先创建你的文本

 textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
   textPaint.setColor(textColor);
   if (textHeight == 0) {
       textHeight = textPaint.getTextSize();
   } else {
       textPaint.setTextSize(textHeight);
   }

   piePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
   piePaint.setStyle(Paint.Style.FILL);
   piePaint.setTextSize(textHeight);

   shadowPaint = new Paint(0);
   shadowPaint.setColor(0xff101010);
   shadowPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));

像这样,您需要设置填充并将其放置在您想要的位置,如下所示

// Account for padding
float xpad = (float)(getPaddingLeft() + getPaddingRight());
float ypad = (float)(getPaddingTop() + getPaddingBottom());

// Account for the label
if (showText) xpad += textWidth;

float ww = (float)w - xpad;
float hh = (float)h - ypad;

// Figure out how big we can make the pie.
float diameter = Math.min(ww, hh);

我从上述 URL 获得了整个代码。

您需要将以下代码添加到中心定位

 Paint yourPaint = new Paint();

  int xP = (canvas.getWidth() / 2);
  int yP = (int) ((canvas.getHeight() / 2) - ((yourPaint .descent()yourPaint .ascent()) / 2)) ;

        canvas.drawText(yourTextView, xP, yP, yourPaint);
于 2019-02-27T03:03:55.737 回答