无法在Android画布中居中文本

时间:2014-04-16 20:07:52

标签: android canvas paint

我正在使用以下代码在圆圈内写“g”。 “g”必须在圆圈内水平和垂直居中。但我不能,我在哪里错了?

//sv is surfaceview which covers whole screen
sv.getHolder().addCallback(new SurfaceHolder.Callback() 
    {

        @Override
        public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void surfaceCreated(SurfaceHolder arg0) {
            // TODO Auto-generated method stub
            // surfaceview width
            swidth=sv.getWidth();
            sheight=sv.getHeight();
            int height = sheight/3;
            int mat = Math.min(height,swidth/2);
            Paint paint= new Paint(Paint.ANTI_ALIAS_FLAG);
            Paint paint1= new Paint(Paint.ANTI_ALIAS_FLAG);
            Resources r = getResources();
            paint.setColor(Color.CYAN);
            paint1.setColor(Color.BLACK);

            Canvas c = sv.getHolder().lockCanvas();
            c.drawARGB(254, 254, 254, 254);
            String t1="g";
            int ttwidth=determineMaxTextSize(t1, mat/4);
            paint1.setTextSize(ttwidth);
            Rect bounds = new Rect();
            paint1.getTextBounds(t1, 0, 3, bounds);
            c.drawCircle(swidth/4, height+height/2, mat/4, paint);
            c.drawText(t1, swidth/4-bounds.width()/2, height+height/2+bounds.height()/2, paint1);



            sv.getHolder().unlockCanvasAndPost(c);

        }

这是上面代码中使用的方法。

private int determineMaxTextSize(String str, float maxWidth)
{
    int size = 0;       
    Paint paint = new Paint();

    do {
        paint.setTextSize(++ size);
    } while(paint.measureText(str) < maxWidth);

    return size;
}

以下是我尝试4种不同文本时的结果。

enter image description here

修改 用这个

编辑我的代码后
            paint1.setTextAlign(Align.CENTER);
            String t1="N";
            int ttwidth=determineMaxTextSize(t1, mat/4);
            paint1.setTextSize(ttwidth);
            Rect bounds = new Rect();
            paint1.getTextBounds(t1, 0, 3, bounds);
            c.drawCircle(swidth/4, height+height/2, mat/4, paint);
            c.drawText(t1, swidth/4, height+height/2+bounds.height()/2, paint1);

我得到的结果更好 enter image description here

但是,您可以看到“g”仍未对齐。

1 个答案:

答案 0 :(得分:0)

 paint1.setTextAlign(Align.CENTER);
        String t1="N";
        int ttwidth=determineMaxTextSize(t1, mat/4);
        paint1.setTextSize(ttwidth);
        Rect bounds = new Rect();
        paint1.getTextBounds(t1, 0, 3, bounds);
        c.drawCircle(swidth/4, height+height/2, mat/4, paint);
        c.drawText(t1, swidth/4, height+height/2+bounds.height()/2, paint1);

以上代码就是答案