Android Canvas Draw drawTextAtCanvasCenter(Canvas canvas, Paint paint, String text)

Here you can find the source of drawTextAtCanvasCenter(Canvas canvas, Paint paint, String text)

Description

draw Text At Canvas Center

Declaration

public static void drawTextAtCanvasCenter(Canvas canvas, Paint paint,
            String text) 

Method Source Code

//package com.java2s;

import android.graphics.Canvas;
import android.graphics.Paint;

public class Main {
    public static void drawTextAtCanvasCenter(Canvas canvas, Paint paint,
            String text) {// w  w w . jav a2s.com
        if (text == null) {
            return;
        }

        final int width = canvas.getWidth();
        final int height = canvas.getHeight();
        int offsetX, offsetY;
        offsetX = calcXWhenAlignCenter(width, paint, text);
        offsetY = calcYWhenAlignCenter(height, paint);
        canvas.drawText(text, offsetX, offsetY, paint);
    }

    public static int calcXWhenAlignCenter(int width, Paint paint,
            String string) {
        if (paint == null) {
            return 0;
        }
        return (int) ((width - paint.measureText(string)) / 2);
    }

    public static int calcYWhenAlignCenter(int height, Paint paint) {
        if (paint == null) {
            return 0;
        }

        final float fontHeight = paint.getFontMetrics().bottom
                - paint.getFontMetrics().top;
        return (int) ((height - fontHeight) / 2 - paint.getFontMetrics().top);
    }
}

Related

  1. drawCross(Bitmap bm, int x, int y)
  2. drawSelect(Bitmap bm, int x, int y, int cellWidth, int cellHeight)
  3. drawText(String strMsg, Canvas g, Paint paint, int setx, int sety, int fg, int bg)
  4. circle(Canvas canvas, int color, int stroke, float x, float y, float radius)
  5. rect(Canvas canvas, int color, int stroke, float x, float y, float width, float height)
  6. add(Bitmap firstlayer, Bitmap secondlayer)
  7. add(Bitmap[] images)