package com.printer.demo.utils;

import android.text.TextPaint;
import java.util.ArrayList;
import java.util.List;

/**
 * 按像素宽度把一段文字拆成多行，不破坏单词（只在空白处断）。
 */
public class TextBreakUtil {

    /**
     * @param text  原始字符串
     * @param maxW  允许的最大像素宽
     * @param paint 用来量宽
     * @return 多行列表
     */
    public static List<String> breakIntoLines(String text, float maxW, TextPaint paint) {
        List<String> lines = new ArrayList<>();
        if (text == null || text.length() == 0) {
            lines.add("");
            return lines;
        }
        char[] chars = text.toCharArray();
        int start = 0, lastSpace = 0;
        float lineW = 0;
        for (int i = 0; i < chars.length; i++) {
            float cw = paint.measureText(chars, i, 1);
            if (chars[i] == ' ' || chars[i] == '\t') lastSpace = i;
            if (lineW + cw <= maxW) {          // 还能放
                lineW += cw;
            } else {                            // 放不下了
                if (lastSpace > start) {        // 有空格，从空格断
                    lines.add(new String(chars, start, lastSpace - start));
                    start = lastSpace + 1;
                } else {                        // 超长单词，硬断
                    lines.add(new String(chars, start, i - start));
                    start = i;
                }
                lineW = paint.measureText(chars, start, i - start + 1);
            }
        }
        if (start < chars.length) lines.add(new String(chars, start, chars.length - start));
        if (lines.isEmpty()) lines.add("");
        return lines;
    }
}