Get sub String Length via TextPaint - Android android.text

Android examples for android.text:TextPaint

Description

Get sub String Length via TextPaint

Demo Code

import android.text.TextPaint;
import android.text.TextUtils;

public class Main {

  public static int subStringLength(String str, int maxPix, TextPaint paint) {
    if (TextUtils.isEmpty(str)) {
      return 0;// ww  w . j a  v  a 2  s  .co m
    }
    int currentIndex = 0;
    for (int i = 0; i < str.length(); i++) {
      String temp = str.substring(0, i + 1);
      float valueLength = paint.measureText(temp);
      if (valueLength > maxPix) {
        currentIndex = i - 1;
        break;
      } else if (valueLength == maxPix) {
        currentIndex = i;
        break;
      }
    }
    if (currentIndex == 0) {
      currentIndex = str.length() - 1;
    }
    return currentIndex;
  }

}

Related Tutorials