在 dart 中创建旋转矩形

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

我有一个有趣的问题。我正在颤动的画布上绘制一个矩形。我使用 Rect 对象来定义矩形的外观。如果我使用画布旋转功能,我会得到所需的结果。如果我尝试手动创建一个旋转的矩形,它就无法正常工作。这是我旋转矩形的函数

  static Rect rotateRect(Rect rect, Offset center, double angle) {
final Offset leftTop = rotateOffset(rect.topLeft, center, angle);
final Offset bottomLeft = rotateOffset(rect.bottomLeft, center, angle);

final Offset rightTop = rotateOffset(rect.topRight, center, angle);
final Offset bottomRight = rotateOffset(rect.bottomRight, center, angle);

return Rect.fromPoints(leftTop, bottomRight);}

这是结果(绿色是使用画布旋转并且是正确的,紫色是使用我的旋转函数尝试构建旋转的矩形):

如您所见,由于仅使用两个点来创建矩形,因此只有左上角和右下角的点是正确的。我尝试的所有方法似乎都不允许我获得旋转的矩形。

请注意,我只是在寻找在 Rect 对象内构建矩形的解决方案。我并不是在寻找其他策略来在画布上达到相同的效果。

flutter dart canvas rotation rectangles
1个回答
0
投票

为了在 Dart 中的 Rect 对象内创建旋转的矩形,可以使用以下函数:

import 'dart:math';
import 'package:flutter/painting.dart';

Rect rotateRect(Rect rect, Offset center, double angle) {
  final double centerX = center.dx;
  final double centerY = center.dy;

  final double dx = rect.center.dx - centerX;
  final double dy = rect.center.dy - centerY;

  final double rotatedDx = dx * cos(angle) - dy * sin(angle);
  final double rotatedDy = dx * sin(angle) + dy * cos(angle);

  final double newCenterX = centerX + rotatedDx;
  final double newCenterY = centerY + rotatedDy;

  final double width = rect.width;
  final double height = rect.height;

  return Rect.fromCenter(center: Offset(newCenterX, newCenterY), width: width, height: height);
}

该函数将原始矩形、中心点和旋转角度作为输入参数,并在 Rect 对象内返回一个新的旋转矩形。

© www.soinside.com 2019 - 2024. All rights reserved.