Android文本切割成多个bitmap

Android文本切割成多个bitmap,切割之前必须考虑,当字符过多的时候,要处理字符换行,有两种方案:

方案1:StaticLayout在Android中实现自动换行多行文本

TextPaint textPaint = new TextPaint();
textPaint.setARGB(0xFF, 0, 0, 0);
textPaint.setTextSize(20.0F);
textPaint.setAntiAlias(true);
StaticLayout layout = new StaticLayout("Constructs a new exception with the specified detail message,cause, suppression enabled or disabled, and writable stacktrace enabled or disabled.", textPaint, 300,Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
canvas.save();
canvas.translate(20, 20);
layout.draw(canvas);
canvas.restore();

方案2:使用 \n 来分割字符传,一部分一部分绘制

String[] strings = text.split("\n");
Paint.FontMetrics fm = paint.getFontMetrics();
float offsetY = fm.descent - fm.ascent;
for (String s : strings) {
     canvas.drawText(s , i, 1, currentX, currentY - ascent, paint);
     currentY += offsetY;
     offsetY = 0;
     currentX = 0;
}

本文使用方案1进行文本切割成多个bitmap,应用场景在打印机打印小图,提高打印速度

国际规则,核心代码如下:

            List bitmaps = new ArrayList();
            StaticLayout sl = new StaticLayout(text, textPaint, 300, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            int lineCount = sl.getLineCount();
            for (int i = 0; i < lineCount; i++) {
                float lineWidth = sl.getLineWidth(i);
                int lineStart = sl.getLineStart(i);
                int lineEnd = sl.getLineEnd(i);
                //关键地方,根据索引获取每一行字符,再使用Canvas绘制
                String lineText = text.substring(lineStart, lineEnd);
                Bitmap blockBitmap = Bitmap.createBitmap((int) lineWidth, fontHeight, Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(blockBitmap);
                canvas.drawColor(Color.WHITE);
                canvas.drawText(lineText, (float)parameter.paintX(), (float)fontHeight, mTextPaint);
                bitmaps.add(blockBitmap);
            }

StaticLayout参数说明:

/**
 * @param source 需要分行的字符串
 * @param bufstart 需要分行的字符串从第几的位置开始
 * @param bufend 需要分行的字符串到哪里结束
 * @param paint 画笔对象
 * @param outerwidth layout的宽度,超出时换行
 * @param align layout的对其方式,有ALIGN_CENTER, ALIGN_NORMAL, ALIGN_OPPOSITE 三种
 * @param spacingmult 相对行间距,相对字体大小,1.5f表示行间距为1.5倍的字体高度。
 * @param spacingadd 在基础行距上添加多少
 * @param includepad 未知
 * @param ellipsize 从什么位置开始省略
 * @param ellipsizedWidth 超过多少开始省略
 */
public StaticLayout(CharSequence source, int bufstart, int bufend,
                    TextPaint paint, int outerwidth,
                    Alignment align,
                    float spacingmult, float spacingadd,
                    boolean includepad,
                    TextUtils.TruncateAt ellipsize, int ellipsizedWidth) {
    this(source, bufstart, bufend, paint, outerwidth, align,
            TextDirectionHeuristics.FIRSTSTRONG_LTR,
            spacingmult, spacingadd, includepad, ellipsize, ellipsizedWidth, Integer.MAX_VALUE);
}

高版本使用Builder创建StaticLayout,而TextView也用到了StaticLayout

你可能感兴趣的:(Android文本切割成多个bitmap)