You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何在Canvas上绘制带旋转角度的倾斜文本?

Canvas 绘制倾斜文本解决方案

在Canvas场景下可以通过坐标系变换+状态保存的方式实现文本旋转,无需依赖Widget层的旋转能力,修改后的绘制函数如下:

import 'dart:math' as math;

void drawText(Canvas canvas, Offset center, String text, Color color,
    Color bgColor, double fontSize, double angle) { // 新增angle参数,单位为弧度
  TextSpan span = TextSpan(
      style: TextStyle(
          color: color,
          backgroundColor: bgColor,
          fontWeight: FontWeight.bold,
          fontSize: fontSize),
      text: text);
  TextPainter tp = TextPainter(
      text: span,
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr);
  tp.layout();

  // 核心变换逻辑
  canvas.save(); // 保存当前画布状态
  canvas.translate(center.dx, center.dy); // 将坐标系原点平移到文本绘制中心点
  canvas.rotate(angle); // 旋转坐标系,顺时针为正方向
  // 绘制时偏移半个文本宽高,让文本中心与旋转中心重合
  tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2));
  canvas.restore(); // 恢复画布状态,避免旋转影响后续其他绘制内容
}

使用说明

  • angle参数为弧度值,如果你使用的是角度单位,需要先转换为弧度:角度值 * math.pi / 180,例如旋转30度就传入30 * math.pi / 180
  • 旋转中心默认为传入的文本中心点center,如果需要调整旋转中心,修改translate的偏移参数即可

效果参考:
倾斜文本效果参考图

内容的提问来源于stack exchange,提问作者dramaticlook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:36:04