使用画布垂直和水平居中文本

gre*_*f82 9 android drawtext android-canvas

我正在尝试水平和垂直对齐位图中的文本,我读了几篇文章,但我找不到解决方案.位图是一个简单的圆形图像.我发布了当前的代码.它或多或少都有效,但是文本没有完全居中,它看起来有点在左边,有点在顶部,我的意思是我似乎必须添加一个偏移来将它移动到右边和底部.

public static float convertDpToPixel(float dp, Context context) {
     Resources resources = context.getResources();
     DisplayMetrics metrics = resources.getDisplayMetrics();
     float px = dp * (metrics.densityDpi / 160f);
     return px;
}    

v = (ImageView) findViewById(R.id.imageView1);
Bitmap b = BitmapFactory.decodeResource(getResources(),
               R.drawable.marker).copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(b);
Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setARGB(255, 0, 0, 0);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setTextSize(convertDpToPixel(9, this));

String text = "30";
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() +
               textPaint.ascent()) / 2)) ;

canvas.drawText(text, xPos, yPos, textPaint);
v.setImageBitmap(b);
Run Code Online (Sandbox Code Playgroud)

Mer*_*ede 28

问题是你目前没有考虑文本的宽度和高度.如果你的文字是"hello"或"THIS A STRING"你只是平等对待它,那就错了.

您需要计算文本的宽度和高度,然后将文本位置移动一半距离.

例如,垂直居中:

Rect r = new Rect();
paint.getTextBounds(text, 0, text.length(), r);
yPos += (Math.abs(r.height()))/2;    // or maybe -= instead of +=, depends on your coordinates
Run Code Online (Sandbox Code Playgroud)

我希望这会带你走向正确的方向.

编辑:根据绘画中的"对齐"设置解释原点.你正在使用

 textPaint.setTextAlign(Align.CENTER);
Run Code Online (Sandbox Code Playgroud)

因此,您可能不需要进行任何计算以水平居中(这意味着对于水平原点,您应该使用已有的代码).

 int xPos = (canvas.getWidth() / 2);
Run Code Online (Sandbox Code Playgroud)


ces*_*rds 17

正如@Merlevede所说,如果你将textPaint与CENTER对齐,你只需要:

canvas.drawText(
    text,
    canvas.getWidth() / 2,
    ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)),
    textPaint
);
Run Code Online (Sandbox Code Playgroud)