draw Text on Canvas by max pixel width - Android android.graphics

Android examples for android.graphics:Canvas

Description

draw Text on Canvas by max pixel width

Demo Code

import java.util.ArrayList;
import java.util.List;

import android.graphics.Canvas;
import android.graphics.Paint.FontMetrics;
import android.text.TextPaint;
import android.text.TextUtils;

public class Main {

  public static int drawText(Canvas canvas, String text, int maxWPix, TextPaint paint, int left, int top) {
    if (TextUtils.isEmpty(text)) {
      return 1;//w ww  .  j av a  2 s  .c o m
    }
    List<String> mStrList = getDrawRowStr(text, maxWPix, paint);

    int hSize = (int) getDesiredHeight(paint);

    for (int i = 0; i < mStrList.size(); i++) {
      // ??????
      int x = left;
      int y = top + hSize / 2 + hSize * i;
      String textLine = mStrList.get(i);
      canvas.drawText(textLine, x, y, paint);

    }
    return mStrList.size();
  }

  public static List<String> getDrawRowStr(String text, int maxWPix, TextPaint paint) {
    String[] texts = null;
    if (text.indexOf("\n") != -1) {
      texts = text.split("\n");
    } else {
      texts = new String[1];
      texts[0] = text;
    }
    List<String> mStrList = new ArrayList<String>();

    for (int i = 0; i < texts.length; i++) {
      String textLine = texts[i];
      while (true) {
        int endIndex = subStringLength(textLine, maxWPix, paint);
        if (endIndex <= 0) {
          mStrList.add(textLine);
        } else {
          if (endIndex == textLine.length() - 1) {
            mStrList.add(textLine);
          } else {
            mStrList.add(textLine.substring(0, endIndex + 1));
          }

        }
        if (textLine.length() > endIndex + 1) {
          textLine = textLine.substring(endIndex + 1);
        } else {
          break;
        }
      }
    }

    return mStrList;
  }

  public static int subStringLength(String str, int maxPix, TextPaint paint) {
    if (TextUtils.isEmpty(str)) {
      return 0;
    }
    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;
  }

  public static float getDesiredHeight(TextPaint paint) {
    FontMetrics fm = paint.getFontMetrics();
    return (float) Math.ceil(fm.descent - fm.ascent);
  }

}

Related Tutorials