Code Snipe - 自动换行分隔字符串代码

自动换行分隔字符串代码

/** 
 * 自动分割文本 
 * @param content 需要分割的文本 
 * @param p  画笔,用来根据字体测量文本的宽度 
 * @param width 最大的可显示像素(一般为控件的宽度) 
 * @return 一个字符串数组,保存每行的文本 
 */  
public String[] autoSplit(String content, TextPaint p, float width) {
    
    if (width <= 0) {
        return null;
    }
    int length = content.length();
    Rect bounds = new Rect();
    p.getTextBounds(content, 0, content.length(), bounds);
    float textWidth = bounds.width();
    if (textWidth <= width) {
        return new String[]{content};
    }

    int start = 0, end = 1, i = 0;
    int lines = (int) Math.ceil(textWidth / width); //计算行数
    String[] lineTexts = new String[lines];
    while (start < length && end < length) {
        if (p.measureText(content, start, end) >= width) {
            lineTexts[i++] = content.substring(start, end - 1);
            start = end - 1;
            end--;
        }
        end++;
    }

    if (i < lineTexts.length)
        lineTexts[i++] = content.substring(start, end);

    return lineTexts;
}

你可能感兴趣的:(Code Snipe - 自动换行分隔字符串代码)