在画布上的Andr​​oid中心文画布、中心、Andr、oid

由网友(伊佃)分享简介:我想显示使用下面的code文本。现在的问题是,该文本不是水平居中。当我设置为的drawText 的坐标,它设置在此位置文本的底部。我想绘制的文本,该文本也居中水平。这是一个图片,以进一步显示我的问题:@覆盖保护无效的OnDraw(帆布油画){// TODO自动生成方法存根super.onDraw(画布);//ca...

我想显示使用下面的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);

阅读全文

相关推荐

最新文章