如何在图像沿着给定路径移动时旋转图像?

问题描述 投票:0回答:1

在我的应用程序中,我有一张沿着某条路径移动的乌龟的图像。我想在每次乌龟在其路径上“转动”时旋转乌龟,这样它看起来更好。这是我的 CustomPaint 类:

class MyPainter extends CustomPainter {
  ui.Image? image;
  double _width = 0;
  double _height = 0;
  int _ratio = 0;
  final double _progress;

  MyPainter(width, height, ratio, this._progress, [this.image]) {
    _width = width;
    _height = height;
    _ratio = ratio * 10;
  }

  @override
  void paint(Canvas canvas, Size size) async {
    Paint linePaint = Paint()
      ..strokeWidth = 20
      ..strokeCap = StrokeCap.butt
      ..style = PaintingStyle.stroke;

    var path = getPath();
    ui.PathMetrics pathMetrics = path.computeMetrics();
    ui.PathMetric pathMetric = pathMetrics.elementAt(0);
    final pos = pathMetric.getTangentForOffset(pathMetric.length * _progress);
    Path extracted = pathMetric.extractPath(0.0, pathMetric.length * _progress);

    linePaint.strokeWidth = 6;

    canvas.drawPath(extracted, linePaint);
    if (image == null) {
      canvas.drawCircle(pos!.position, linePaint.strokeWidth / 2, linePaint);
    } else {
      Offset location = Offset(pos!.position.dx - image!.width / 2, pos.position.dy);
      canvas.save();
      double cx = pos.position.dx;
      double cy = pos.position.dy + image!.height / 2;
      rotateTurtle(canvas: canvas, cx: cx, cy: cy, angle: 90);
      
      canvas.drawPoints(ui.PointMode.points, [Offset(cx, cy)], linePaint);
      canvas.drawImage(image!, location, linePaint);
      canvas.restore();
      
    }
  }

  void rotateTurtle({required Canvas canvas,
      required double cx,
      required double cy,
      required double angle}){
        canvas.translate(cx, cy);
        canvas.rotate(angle * math.pi / 180);
        canvas.translate(-cx, -cy);
  }

  Path getPath() {
    return Path()
      ..moveTo(_width, _height)
      ..lineTo(_width + _ratio, _height)
      ..lineTo(_width + _ratio, _height)
      ..lineTo(_width + _ratio, _height - _ratio)
      ..lineTo(_width - _ratio, _height - _ratio)
      ..lineTo(_width - _ratio, _height + _ratio);
  }

  @override
  bool shouldRepaint(covariant MyPainter oldDelegate) {
    return oldDelegate._progress != _progress;
  }
}

它所采取的路径是这样的:

path

我已经成功地在动画开始时将图像旋转到任意角度。

怎样才能让乌龟每次转弯时向左旋转90度?

flutter dart flutter-animation
1个回答
0
投票

正如@pskink建议的那样,我应该在这里使用

pos.angle
,如下所示:

rotateTurtle(canvas: canvas, cx: cx, cy: cy, angle: pos.angle);  
© www.soinside.com 2019 - 2024. All rights reserved.