Android画布上居中文本

231
我试图使用以下代码显示文本。 问题是文本水平居中显示不正确。 当我为drawText设置坐标时,它将文本的底部放置在该位置。我希望文本在水平方向上也能居中绘制。
这是一张图片,进一步展示了我的问题: Screenshot
@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    //canvas.drawRGB(2, 2, 200);
    Paint textPaint = new Paint();
    textPaint.setARGB(200, 254, 0, 0);
    textPaint.setTextAlign(Align.CENTER);
    textPaint.setTypeface(font);
    textPaint.setTextSize(300);
    canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2  , textPaint);
}

20
不要在onDraw事件中声明你的paint对象,它会在每次重绘时重新创建。考虑将其作为私有类变量声明。 - Christopher Rathgeb
10
伙计! 请注明您的图像链接是NSFW! 我并不保守,但我不想在办公室屏幕上出现露胸女性的广告。 - Michael Scheper
5
抱歉,@MichaelScheper,我已经更新了链接! - Sebastian
只是简单回答一下为什么你的文本只水平居中。Paint.Align.CENTER 表示文本将在参考点上水平居中显示。在这里查看注释:https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android11-gsi/graphics/java/android/graphics/Paint.java#530 - BamsBamx
12个回答

444

尝试以下内容:

 Paint textPaint = new Paint();
 textPaint.setTextAlign(Paint.Align.CENTER);

 int xPos = (canvas.getWidth() / 2);
 int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ; 
 //((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.

 canvas.drawText("Hello", xPos, yPos, textPaint);

10
非常好的回答。对于我而言,我需要将文本水平居中,而不是让文本从中心位置开始:int xPos = (宽度 - 文本画笔.文字大小 * Math.Abs(_text.Length / 2)) / 2; 不确定是否有更好的方法来实现这一点。 - paj7777
65
如果您设置textPaint.setTextAlign(Align.CENTER),那么paj7777就不是必需的。 - Costi Muraru
@paj7777 无论如何,那只对于固定宽度字体有效。而且,你不需要将其转换为浮点数;如果你除以一个浮点数,结果将会是一个浮点数。例如:float halfLength = text.length() / 2f; 这被称为类型提升 - Michael Scheper
阿伦:你为什么要将其转换为intCanvas.drawText()使用float作为坐标,所以如果你坚持使用float,你的文本将更可靠地居中。 - Michael Scheper
2
我在下面的回答中将使用中心点和 Paint.descent() 以及 Paint.ascent() 来居中文本这种方法与使用 Paint.getTextBounds() 居中文本这种方法进行了比较。Paint.descent()Paint.ascent() 并不考虑实际的文本内容。(您可以在下面的帖子中的截图中看到这种不准确性。)这就是为什么我建议不要使用这种方法。使用 Paint.getTextBounds() 的方法似乎更为精确。 - andreas1724
显示剩余2条评论

263

使用Paint.getTextBounds()进行居中:

在此输入图片描述

private Rect r = new Rect();

private void drawCenter(Canvas canvas, Paint paint, String text) {
    canvas.getClipBounds(r);
    int cHeight = r.height();
    int cWidth = r.width();
    paint.setTextAlign(Paint.Align.LEFT);
    paint.getTextBounds(text, 0, text.length(), r);
    float x = cWidth / 2f - r.width() / 2f - r.left;
    float y = cHeight / 2f + r.height() / 2f - r.bottom;
    canvas.drawText(text, x, y, paint);
}
  • Paint.Align.CENTER并不意味着文本的参考点垂直居中。参考点总是在基线上。那么,为什么不使用Paint.Align.LEFT呢?无论如何都必须计算参考点。

  • Paint.descent()的缺点在于它没有考虑实际文本。无论文本是否包含具有下行的字母,Paint.descent()都会检索相同的值。这就是为什么我改用r.bottom

  • 我在API<16时遇到了一些问题,所以我改用Canvas.getClipBounds(Rect)。(不要使用Canvas.getClipBounds().getHeight(),因为它为Rect分配内存。)

  • 出于性能原因,应在它们在onDraw()中使用之前分配对象。由于drawCenter()将在onDraw()中调用,因此在此处作为字段预分配了对象Rect r


我尝试将两个最佳答案的代码放入我的代码中(2015年8月),并制作了一个截图进行比较:

居中文本的三种版本

文本应该在红色填充矩形内居中。我的代码生成白色文本,而另外两个代码生成灰色文本(它们实际上是相同的,重叠的)。灰色文本有点太低且太靠右。

这是我进行测试的方式:

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

class MyView extends View {

    private static String LABEL = "long";
    private static float TEXT_HEIGHT_RATIO = 0.82f;

    private FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(0, 0);
    private Rect r = new Rect();
    private Paint paint = new Paint();
    private Paint rectPaint = new Paint();

    public MyView(Context context) {
        super(context);
    }

    private void drawTextBounds(Canvas canvas, Rect rect, int x, int y) {
        rectPaint.setColor(Color.rgb(0, 0, 0));
        rectPaint.setStyle(Paint.Style.STROKE);
        rectPaint.setStrokeWidth(3f);
        rect.offset(x, y);
        canvas.drawRect(rect, rectPaint);
    }

    // andreas1724 (white color):
    private void draw1(Canvas canvas, Paint paint, String text) {
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setColor(Color.rgb(255, 255, 255));
        canvas.getClipBounds(r);
        int cHeight = r.height();
        int cWidth = r.width();
        paint.getTextBounds(text, 0, text.length(), r);
        float x = cWidth / 2f - r.width() / 2f - r.left;
        float y = cHeight / 2f + r.height() / 2f - r.bottom;
        canvas.drawText(text, x, y, paint);
        drawTextBounds(canvas, r, (int) x, (int) y);
    }

    // Arun George (light green color):
    private void draw2(Canvas canvas, Paint textPaint, String text) {
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(Color.argb(100, 0, 255, 0));
        int xPos = (canvas.getWidth() / 2);
        int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2));
        canvas.drawText(text, xPos, yPos, textPaint);
    }

    // VinceStyling (light blue color):
    private void draw3(Canvas yourCanvas, Paint mPaint, String pageTitle) {
        mPaint.setTextAlign(Paint.Align.LEFT);
        mPaint.setColor(Color.argb(100, 0, 0, 255));
        r = yourCanvas.getClipBounds();
        RectF bounds = new RectF(r);
        bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
        bounds.bottom = mPaint.descent() - mPaint.ascent();
        bounds.left += (r.width() - bounds.right) / 2.0f;
        bounds.top += (r.height() - bounds.bottom) / 2.0f;
        yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int margin = 10;
        int width = w - 2 * margin;
        int height = h - 2 * margin;
        params.width = width;
        params.height = height;
        params.leftMargin = margin;
        params.topMargin = margin;
        setLayoutParams(params);
        paint.setTextSize(height * TEXT_HEIGHT_RATIO);
        paint.setAntiAlias(true);
        paint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD_ITALIC));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.rgb(255, 0, 0));
        draw1(canvas, paint, LABEL);
        draw2(canvas, paint, LABEL);
        draw3(canvas, paint, LABEL);
    }
}

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        FrameLayout container = new FrameLayout(this);
        container.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        container.addView(new MyView(this));
        setContentView(container);
    }
}

1
非常感谢您。您的逻辑确实帮了我很多。 - Sujay U N
非常感谢您。您的逻辑确实也帮了我很多! - LiuWenbin_NO.
这是唯一真正将文本居中的答案。 - Joery

72

垂直对齐很难,因为文本下降和上升发生了变化,许多人使用Paint.getTextBounds()来检索TextWidth和TextHeight,但它并不能使文本中心更加居中。在这里,我们可以使用Paint.measureText()来计算TextWidth,TextHeight我们只需通过下降和上升进行减法即可,然后我们获得了最接近的TextSize,以下工作对彼此而言非常容易。

// the Paint instance(should be assign as a field of class).
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(getResources().getDimension(R.dimen.btn_textsize));

// the display area.
Rect areaRect = new Rect(0, 0, 240, 60);

// draw the background style (pure color or image)
mPaint.setColor(Color.BLACK);
yourCanvas.drawRect(areaRect, mPaint);

String pageTitle = "文字小说";

RectF bounds = new RectF(areaRect);
// measure text width
bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
// measure text height
bounds.bottom = mPaint.descent() - mPaint.ascent();

bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;

mPaint.setColor(Color.WHITE);
yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);

代码截图

顺便提一下,我们强烈建议使用RectF而不是Rect,因为位置需要更精确的值,在我的经验中,RectF在xhdpi设备上只会出现上下偏差一个像素,而Rect则会多两个。


如所述,变量“Paint”令人困惑。它是如何分配的?它如何知道文本的上升和下降以用于bounds.bottom? - RoundSparrow hilltx
1
是的,我针对这个进行了优化,请看一下。 - VinceStyling
谢谢您节省了我宝贵的时间)) - Andrew

17

你的代码绘制文本基线中心点在视图中心。为了将文本居中于某个点x,y,你需要计算文本的中心点,并将该点放置在目标点。

这个方法会在点x,y处绘制居中的文本。如果你传入视图的中心点,它会绘制居中的文本。

private void drawTextCentered(String text, int x, int y, Paint paint, Canvas canvas) {
    int xPos = x - (int)(paint.measureText(text)/2);
    int yPos = (int) (y - ((textPaint.descent() + textPaint.ascent()) / 2)) ;

    canvas.drawText(text, xPos, yPos, textPaint);
}

@MarcioGranzotto 正在使用 android.graphics.Paint 来绘制文本。 - William Reed

5

使用以下方式对我有用:textPaint.textAlign = Paint.Align.CENTER结合textPaint.getTextBounds

private fun drawNumber(i: Int, canvas: Canvas, translate: Float) {
            val text = "$i"
            textPaint.textAlign = Paint.Align.CENTER
            textPaint.getTextBounds(text, 0, text.length, textBound)

            canvas.drawText(
                    "$i",
                    translate + circleRadius,
                    (height / 2 + textBound.height() / 2).toFloat(),
                    textPaint
            )
        }

结果是:

这里输入图片描述


这张图片展示了一个结果。

4

我发现将文本居中的最佳解决方案如下:

textPaint.setTextAlign(Paint.Align.CENTER);
//textPaint is the Paint object being used to draw the text (it must be initialized beforehand)
float textY=center.y;
float textX=center.x; 
// in this case, center.x and center.y represent the coordinates of the center of the rectangle in which the text is being placed
canvas.drawText(text,textX,textY,textPaint);    `

2
这看起来就像提问者尝试居中文本的方式。由于Paint.Align.Center并不意味着文本的参考点在垂直方向上居中,因此文本将无法在垂直方向上居中。 - andreas1724

2
这对我有用:

这对我有用:

 paint.setTextAlign(Paint.Align.CENTER);
        int xPos = (newWidth / 2);
        int yPos = (newHeight / 2);
        canvas.drawText("Hello", xPos, yPos, paint);

如果有任何问题,请告知我。


它将从中心点开始书写文本,但整个文本不会居中。 - M Shaban Ali

2
我创建了一个方法来简化这个过程:
    public static void drawCenterText(String text, RectF rectF, Canvas canvas, Paint paint) {
    Paint.Align align = paint.getTextAlign();
    float x;
    float y;
    //x
    if (align == Paint.Align.LEFT) {
        x = rectF.centerX() - paint.measureText(text) / 2;
    } else if (align == Paint.Align.CENTER) {
        x = rectF.centerX();
    } else {
        x = rectF.centerX() + paint.measureText(text) / 2;
    }
    //y
    metrics = paint.getFontMetrics();
    float acent = Math.abs(metrics.ascent);
    float descent = Math.abs(metrics.descent);
    y = rectF.centerY() + (acent - descent) / 2f;
    canvas.drawText(text, x, y, paint);

    Log.e("ghui", "top:" + metrics.top + ",ascent:" + metrics.ascent
            + ",dscent:" + metrics.descent + ",leading:" + metrics.leading + ",bottom" + metrics.bottom);
}

rectF是你想要绘制文本的区域,就是这样。 详情


1
在您的onDraw方法中添加以下内容:
paint.setColor(getContext().getResources().getColor(R.color.black));
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Text", (float) getHeight() / 2f, (float) getWidth() / 2f, paint);

1
在您的绘图属性中使用以下内容:
 textPaint.setTextAlign(Paint.Align.CENTER);

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