get Paint Default Text Height - Android Graphics

Android examples for Graphics:Paint

Description

get Paint Default Text Height

Demo Code

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.DisplayMetrics;

public class Main {
  public static int getDefaultTextHeight(String text, Context context) {
    Rect rect = getDefaultTextBounds(text, context);
    return rect.height();
  }/*from  w w  w .  ja  v a 2  s.c  om*/

  public static Rect getDefaultTextBounds(String text, Context context) {
    Paint paint = new Paint();
    paint.setTextSize(toPixel(16, context));
    return getTextBounds(text, paint);
  }

  public static float toPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return px;
  }

  public static Rect getTextBounds(String text, Paint paint) {
    Rect rect = new Rect();
    paint.getTextBounds(text, 0, text.length(), rect);
    return rect;
  }
}

Related Tutorials