天天看點

Android 擷取 TextView 顯示的字元串寬度

轉自 http://www.tuicool.com/articles/JVnMbua

工作上有業務需要判斷textview是否換行,我的做法是判斷textview要顯示的字元串的寬度是否超過我設定的寬度,若超過則會執行換行。

項目中的其他地方也有這樣的需求,故直接使用了那一塊的代碼。如下

public float getTextWidth(Context Context, String text, int textSize){
		TextPaint paint = new TextPaint();
		float scaledDensity = Context.getResource().getDisplayMetrics().scaledDensity;
		paint.setTextSize(scaledDensity * textSize);
		return paint.measureText(text);
	}
           

這裡是使用了TextPaint的measureText方法。

不過在項目實踐上發現了這個方法存在一些問題。當字元串存在字母數字時,就會有1-2像素的誤差。也正是這個誤差,導緻代碼上判斷換行錯誤,使得界面上顯示出錯。

為了解決這個問題,搜到了這篇文章 戳我

這篇文章中使用了另外一個方法測量,沒有new TextPaint,而是使用了TextView自己的TextPaint,這個Paint通過 TextView.getPaint() 方法獲得。

最後給出一個例子來看這兩種方法的差别。

測試機是MI4,xxdpi

代碼如下

public class MainActivity extends Activity {
	
	private final static String TAG = "MainActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// 測試字元串
		// 測試例子均用15sp的字型大小
		String text = "測試中文";
		
		TextView textView = (TextView) findViewById(R.id.test);
		textView.setText(text);
		
		int spec = MeasureSpec.makeMeasureSpec(, MeasureSpec.UNSPECIFIED);
		textView.measure(spec, spec);
		
		// getMeasuredWidth
		int measuredWidth = textView.getMeasuredWidth();
		
		// new textpaint measureText
		TextPaint newPaint = new TextPaint();
		float textSize = getResources().getDisplayMetrics().scaledDensity * ;
		newPaint.setTextSize(textSize);
		float newPaintWidth = newPaint.measureText(text);
		
		// textView getPaint measureText
		TextPaint textPaint = textView.getPaint();
		float textPaintWidth = textPaint.measureText(text);
		
		Log.i(TAG, "測試字元串:" + text);
		Log.i(TAG, "getMeasuredWidth:" + measuredWidth);
		Log.i(TAG, "newPaint measureText:" + newPaintWidth);
		Log.i(TAG, "textView getPaint measureText:" + textPaintWidth);
		
	}
}