flutter - 使用CustomPaint在 Canvas 上居中放置项目

标签 flutter dart flutter-layout

我尝试使用Flutter中的CanvasCustomPainter中的项目居中,范围从TextPaints到普通圆圈。
通常,在将自定义颜料居中时,我会将Offset设置为Offset(size.width/2, size.height/2)。但这不起作用,我的项目被拉到 Canvas 的右下角。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Container(
      child: LayoutBuilder(builder: (context, constraints) {
        return Container(
          width: constraints.widthConstraints().maxWidth,
          height: constraints.widthConstraints().maxHeight,
          child: CustomPaint(
            painter: FollowPainter(),
          ),
        );
      }),
    ));
  }
}

class FollowPainter extends CustomPainter {
  static final fill = Paint()..color = Colors.black;
  @override
  void paint(Canvas canvas, Size size) {
    TextSpan span = new TextSpan(
        style: new TextStyle(
            color: Colors.black, fontSize: 50, fontWeight: FontWeight.w700),
        text: 'Hello World');
    TextPainter tp = new TextPainter(
        text: span,
        textAlign: TextAlign.left,
        textDirection: TextDirection.ltr);
    tp.layout();
    tp.paint(canvas, new Offset(size.width / 2, size.height / 2));
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    throw UnimplementedError();
  }
我怀疑问题可能是因为我是从该偏移开始绘制,而不是从中心开始绘制。
那么如何在CustomPainter中将绘制的小部件居中?

最佳答案

I suspect that the problem could be the fact that I'm starting the drawing from that Offset, instead of drawing from the center.


您是对的,只需从宽度减去文本宽度的一半,再从高度减去文本高度的一半。
tp.paint(canvas, new Offset(size.width / 2 - tp.width / 2, size.height / 2 - tp.height / 2));

关于flutter - 使用CustomPaint在 Canvas 上居中放置项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63059326/

相关文章:

flutter - 如何完全删除 Dart ubuntu?

oop - 如何在dart/flutter中将变量内容传递给参数值?

flutter 有向图。我可以将 CustomPainter 类与自定义小部件一起使用吗?

具有自定义布局和动画的 Flutter Collapsible Appbar

flutter - RenderCustomMultiChildLayoutBox 的每个 child 都必须在其父数据中有一个 ID

dart - 如何读取此值并将其分配给 sqlite Flutter 中的变量?

angular - Dart Angular 组件OptionGroup:LabelFunction

flutter : Custom Radio Button

Flutter - 键盘显示和隐藏导致构建调用

firebase-realtime-database - Flutter:Firebase 基本查询或基本搜索代码