围绕其中心旋转绘制的文本

Rotate painted text about its center

我正在尝试围绕 Canvas 的中心旋转绘制在 Canvas 上的文本。相反,在下面的代码中,当我按下浮动按钮时,文本围绕文本​​的左上角旋转。

按下按钮会增加角度,该角度会传递给 CanvasPainter 以绘制文本。

矩形的左上角最初应位于 offset

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  double _angle = 0;
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          child: CustomPaint(
            painter: CanvasPainter(_angle),
            child: Container(),
          )
         ),
        appBar: AppBar(title: Text('Test')),
        floatingActionButton: FloatingActionButton(
          onPressed: () => setState(() => _angle += .1),
          child: const Icon(Icons.add),
      )
      ),
    );
  }
}

class CanvasPainter extends CustomPainter {
  final double angle;
  final Offset offset = Offset(50, 50);
  
  CanvasPainter(this.angle);
  
  @override
  void paint(Canvas canvas, Size size) {
    final fill = TextPainter(
      text: TextSpan(text: 'This is a test', style: TextStyle(fontSize: 80)),
      textDirection: TextDirection.rtl);
    
    fill.layout();
    
    canvas.save();
    //canvas.translate(-fill.width/2, -fill.height/2);
    canvas.rotate(angle);
    canvas.translate(offset.dx, offset.dy);
      
    fill.paint(canvas, Offset.zero);
    
    canvas.restore();
  }
  
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

这是你必须做的:

[...]
canvas.save();
final pivot = fill.size.center(offset); 
canvas.translate(pivot.dx, pivot.dy); 
canvas.rotate(angle);
canvas.translate(-pivot.dx, -pivot.dy);
fill.paint(canvas, offset);
canvas.restore();