画布上的 Android 中心文本 [英] Android Center text on canvas

查看:27
本文介绍了画布上的 Android 中心文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码显示文本.问题是文本没有水平居中.当我为 drawText 设置坐标时,它会在此位置设置文本的底部.我想绘制文本,以便文本也水平居中.

I'm trying to display a text using the code below. The problem is that the text is not centered horizontally. When I set the coordinates for drawText, it sets the bottom of the text at this position. I would like the text to be drawn so that the text is centered also horizontally.

这是进一步显示我的问题的图片:

This is a picture to display my problem further:

@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);
}

推荐答案

尝试以下操作:

 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);

这篇关于画布上的 Android 中心文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆