在画布上的Andr​​oid中心文 [英] Android Center text on canvas

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

问题描述

我想显示使用下面的code文本。 现在的问题是,该文本不是水平居中。 当我设置为的drawText 的坐标,它设置在此位置文本的底部。我想绘制的文本,该文本也居中水平。

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

  @覆盖
保护无效的OnDraw(帆布油画){
    // TODO自动生成方法存根
    super.onDraw(画布);
    //canvas.drawRGB(2,2,200);
    油漆textPaint =新的油漆();
    textPaint.setARGB(200,254,0,0);
    textPaint.setTextAlign(Align.CENTER);
    textPaint.setTypeface(字体);
    textPaint.setTextSize(300);
    canvas.drawText(你好,canvas.getWidth()/ 2,canvas.getHeight()/ 2,textPaint);
}
 

解决方案

请尝试以下操作:

  INT XPOS =(canvas.getWidth()/ 2);
 INT yPos =(int)的((canvas.getHeight()/ 2) - ((textPaint.descent()+ textPaint.ascent())/ 2));
 //((textPaint.descent()+ textPaint.ascent())/ 2)是从基线到中心的距离。

 canvas.drawText(你好,XPOS,yPos,textPaint);
 

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

解决方案

Try the following:

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

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

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