1 /* 2 * Copyright 2012 AndroidPlot.com 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.androidplot.util; 18 19 import android.graphics.Paint; 20 import android.graphics.Rect; 21 22 public class FontUtils { 23 24 /** 25 * Determines the height of the tallest character that can be drawn by paint. 26 * @param paint 27 * @return 28 */ 29 public static float getFontHeight(Paint paint) { 30 Paint.FontMetrics metrics = paint.getFontMetrics(); 31 return (-metrics.ascent) + metrics.descent; 32 //return (-metrics.top) + metrics.bottom; 33 } 34 35 /** 36 * Get the smallest rect that ecompasses the text to be drawn using paint. 37 * @param text 38 * @param paint 39 * @return 40 */ 41 public static Rect getPackedStringDimensions(String text, Paint paint) { 42 Rect size = new Rect(); 43 paint.getTextBounds(text, 0, text.length(), size); 44 return size; 45 } 46 47 /** 48 * Like getPackedStringDimensions except adds extra space to accommodate all 49 * characters that can be drawn regardless of whether or not they exist in text. 50 * This ensures a more uniform appearance for things that have dynamic text. 51 * @param text 52 * @param paint 53 * @return 54 */ 55 public static Rect getStringDimensions(String text, Paint paint) { 56 Rect size = new Rect(); 57 if(text == null || text.length() == 0) { 58 return null; 59 } 60 paint.getTextBounds(text, 0, text.length(), size); 61 size.bottom = size.top + (int) getFontHeight(paint); 62 return size; 63 } 64 65 } 66