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

Flutter中手动构造旋转Rect对象失败问题求助

Flutter Canvas 旋转Rect对象的正确实现方法

你的自定义rotateRect函数错误的核心原因:矩形旋转后,原左上角和右下角点不再是新矩形的最小/最大边界点,Rect.fromPoints(leftTop, bottomRight)会自动取两点的min/max坐标生成轴对齐矩形,这和旋转后的矩形实际边界不符,导致绘制出错误的紫色矩形。

正确实现代码

首先确保你的rotateOffset旋转点函数是正确的(如果还没实现,参考以下代码):

import 'dart:math';

static Offset rotateOffset(Offset offset, Offset center, double angle) {
  double dx = offset.dx - center.dx;
  double dy = offset.dy - center.dy;
  double rotatedX = dx * cos(angle) - dy * sin(angle);
  double rotatedY = dx * sin(angle) + dy * cos(angle);
  return Offset(rotatedX + center.dx, rotatedY + center.dy);
}

然后修改rotateRect函数,通过计算四个旋转后顶点的最小/最大坐标来构造正确的Rect:

static Rect rotateRect(Rect rect, Offset center, double angle) {
  // 旋转矩形的四个顶点
  final Offset topLeft = rotateOffset(rect.topLeft, center, angle);
  final Offset topRight = rotateOffset(rect.topRight, center, angle);
  final Offset bottomLeft = rotateOffset(rect.bottomLeft, center, angle);
  final Offset bottomRight = rotateOffset(rect.bottomRight, center, angle);

  // 提取所有顶点的坐标值
  final List<double> xCoords = [topLeft.dx, topRight.dx, bottomLeft.dx, bottomRight.dx];
  final List<double> yCoords = [topLeft.dy, topRight.dy, bottomLeft.dy, bottomRight.dy];

  // 找出最小/最大的x、y坐标
  double minX = xCoords.reduce((a, b) => a < b ? a : b);
  double maxX = xCoords.reduce((a, b) => a > b ? a : b);
  double minY = yCoords.reduce((a, b) => a < b ? a : b);
  double maxY = yCoords.reduce((a, b) => a > b ? a : b);

  // 构造旋转后矩形的轴对齐包围盒Rect
  return Rect.fromLTRB(minX, minY, maxX, maxY);
}

说明

旋转后的矩形在画布上的实际占据区域是一个轴对齐的包围盒,上述代码通过计算四个旋转顶点的极值坐标,生成的Rect和Canvas自带旋转绘制出的矩形边界完全一致,能解决你看到的紫色矩形错误问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:00:09