get Paint Default Text Bounds - Android Graphics

Android examples for Graphics:Paint

Description

get Paint Default Text Bounds

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 Rect getDefaultTextBounds(String text, Context context) {
    Paint paint = new Paint();
    paint.setTextSize(toPixel(16, context));
    return getTextBounds(text, paint);
  }/*w w  w  . ja v a2  s. c  om*/

  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