Question

I am using following code to write "g" inside a circle. "g" must be centered horizontally and vertically inside the circle. But I am not able to, where am I wrong ?

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

        }

This is the method used in above code.

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

Here is what I get when I try 4 different texts.

enter image description here

EDIT: After editing my code with this

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

I get this outcome which is better enter image description here

However, you can see "g" is still not aligned.

Was it helpful?

Solution

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

Above code is the answer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top