Android:实用的Text工具方法

package cc.makeblock.android.utils;

import android.R.integer;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.FontMetricsInt;

public class MBTextUtils {

	private static final String TAG = "MBTextUtils";

	/**
	 * 改变Paint的TextSize,TextSize自增,递归调用,直到width,height合适。调用此方法之前应该调用paint.setTextSize(1);
	 * @param paint
	 * @param text
	 * @param maxWidth
	 * @param maxHeight
	 */
	public static void changePaintTextSizeToSuitbale(Paint paint, String text, int maxWidth, int maxHeight){
		int textSize = (int) paint.getTextSize();
		int textWidth = 0;
		int textHeight = 0;

		// 1.用FontMetrics对象计算高度
		FontMetricsInt fontMetrics = paint.getFontMetricsInt(); 
		textHeight = fontMetrics.bottom-fontMetrics.top;//详细:(baseY+bottom)-(baseY-top);

		//2.用bounds计算宽度
		Rect bounds = new Rect();  
		paint.getTextBounds(text, 0, text.length(), bounds); 
		textWidth = bounds.right-bounds.left;
		//		Loger.e(TAG, "textSize="+textSize);
		//		Loger.e(TAG, "textWidth="+textWidth+" textHeight="+textHeight);
		//		Loger.e(TAG,"===========================================");
		if (textWidth>maxWidth || textHeight>maxHeight) {
			//刚刚超过
			paint.setTextSize(--textSize);
			return;
		}
		paint.setTextSize(++textSize);
		changePaintTextSizeToSuitbale(paint, text, maxWidth, maxHeight);
	}

	public static int[] getTextWH(Paint paint, String text){
		int textWidth = 0;
		int textHeight = 0;
		// 1.用FontMetrics对象计算高度
		FontMetricsInt fontMetrics = paint.getFontMetricsInt(); 
		textHeight = fontMetrics.bottom-fontMetrics.top;//详细:(baseY+bottom)-(baseY-top);

		//2.用bounds计算宽度
		Rect bounds = new Rect();  
		paint.getTextBounds(text, 0, text.length(), bounds); 
		textWidth = bounds.right-bounds.left;

		int[] wh = {textWidth, textHeight};
		return wh;
	}

}

  

posted @ 2016-02-29 16:46  MakeBetter  阅读(322)  评论(0编辑  收藏  举报