如何在Flutter中使用canvas.drawParagraph绘制竖排文本
Flutter Canvas 实现竖排文本绘制
Flutter 的 Canvas 原生 Paragraph 并未直接支持竖排文本配置(TextDirection 仅支持左右方向),要实现竖排效果,可通过以下两种方案实现:
方案一:旋转画布实现整段竖排
这是最简便的方式,通过旋转画布坐标系,让文本绘制后呈现竖排效果:
修改你的 drawMeasurementTag 方法:
void drawMeasurementTag(Canvas canvas, Rect limitRect) { String text = "this is content"; double textFont = 18; Paragraph paragraph = getTextBuilder(text, textFont, Colors.red); // 获取文本的宽高 paragraph.layout(const ParagraphConstraints(width: double.infinity)); final textWidth = paragraph.width; // 保存画布当前状态 canvas.save(); // 旋转90度(π/2弧度),若要实现从右往左的竖排,可旋转270度 canvas.rotate(pi / 2); // 调整绘制位置,抵消旋转后的坐标系偏移 canvas.drawParagraph(paragraph, Offset(0, -textWidth)); // 恢复画布原始状态 canvas.restore(); } ui.Paragraph getTextBuilder(String text, double textFont, Color color) { Paint paint = Paint(); paint.color = getTagBackgroundColor(); var builder = ui.ParagraphBuilder(ui.ParagraphStyle( textAlign: TextAlign.center, fontSize: textFont, textDirection: TextDirection.ltr, maxLines: 1, )); builder.pushStyle( ui.TextStyle( color: color, textBaseline: TextBaseline.alphabetic, background: paint), ); builder.addText(text); return builder.build(); }
方案二:逐个字符绘制实现精细竖排
如果需要更灵活的排版控制(比如自定义字符间距、单独调整字符位置),可以拆分文本逐个字符绘制:
void drawMeasurementTag(Canvas canvas, Rect limitRect) { String text = "this is content"; double textFont = 18; double charSpacing = 2; // 字符垂直间距 Offset startPos = const Offset(20, 20); // 起始绘制位置 // 遍历每个字符单独绘制 for (int i = 0; i < text.length; i++) { String char = text[i]; Paragraph paragraph = getTextBuilder(char, textFont, Colors.red); paragraph.layout(const ParagraphConstraints(width: double.infinity)); // 计算每个字符的垂直偏移位置 Offset drawPos = Offset( startPos.dx, startPos.dy + i * (paragraph.height + charSpacing), ); canvas.drawParagraph(paragraph, drawPos); } } // getTextBuilder 方法保持不变 ui.Paragraph getTextBuilder(String text, double textFont, Color color) { Paint paint = Paint(); paint.color = getTagBackgroundColor(); var builder = ui.ParagraphBuilder(ui.ParagraphStyle( textAlign: TextAlign.center, fontSize: textFont, textDirection: TextDirection.ltr, maxLines: 1, )); builder.pushStyle( ui.TextStyle( color: color, textBaseline: TextBaseline.alphabetic, background: paint), ); builder.addText(text); return builder.build(); }
说明:方案一适合整段文本统一竖排的场景,方案二适合需要精细化控制字符布局的需求,可根据你要实现的竖排方向(从上到下、从右到左)调整旋转角度或绘制坐标。
内容的提问来源于stack exchange,提问作者wxkly
相关产品推荐
相关产品推荐

