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

Flutter使用Rect.fromCenter绘制正方形时点击点未作为中心点如何解决

问题根因

  1. 参数传递错误:SpriteSquare构造函数第4、5位参数要求是double类型的top、left,但你调用时直接传入了整个Offset实例,类型不匹配导致坐标取值完全异常,是位置随机的核心原因。
  2. 坐标定位逻辑错误:你当前用Rect.fromLTWH绘制时,传入的left/top是矩形左上角坐标,直接传点击坐标作为左上角的话,矩形中心会自动偏移半个正方形的宽高,不符合点击点为中心的需求。

修正方案

两种修改方式二选一即可:

方案1:沿用你计划的Rect.fromCenter实现(推荐)

直接调整SpriteSquare的绘制逻辑,用中心点定位,不需要额外计算左上角坐标:

// sprite_square.dart修改后代码
class SpriteSquare extends NodeWithSize {
  Color color;
  Function handler;
  // 替换原有left/top,存储中心坐标
  double centerX;
  double centerY;

  // 调整构造参数接收中心x、y
  SpriteSquare(Size size, this.color, this.handler, this.centerX, this.centerY) : super(size){
    userInteractionEnabled = true;
  }

  @override handleEvent(SpriteBoxEvent event) {
    handler(event);
    return true;
  }

  @override
  Future<void> paint(Canvas canvas) async {
    canvas.drawRect(
      // 直接用fromCenter方法,传入中心坐标和宽高即可
      Rect.fromCenter(center: Offset(centerX, centerY), width: size.width, height: size.height),
      Paint()..color = color
    );
  }
}

对应修改handleAdd的参数传递:

handleAdd(SpriteBoxEvent event) {
  final clickPos = event.pointerEvent.localPosition;
  final _whitesquare = SpriteSquare(
    const Size(50.0, 50.0), 
    const Color(0xFFFFFFFF), 
    handleRemoveSelf, 
    clickPos.dx, // 对应中心x坐标
    clickPos.dy  // 对应中心y坐标
  );
  _background.addChild(_whitesquare);
  return true;
}

方案2:不改SpriteSquare原有定义,仅修正坐标计算和传参

如果不想修改原有SpriteSquare的字段和绘制逻辑,只需要计算出正方形左上角的正确坐标,同时把参数传对即可:

handleAdd(SpriteBoxEvent event) {
  const squareSize = 50.0;
  final halfSize = squareSize / 2;
  final clickPos = event.pointerEvent.localPosition;
  // 点击坐标减去半宽/半高得到左上角坐标
  final left = clickPos.dx - halfSize;
  final top = clickPos.dy - halfSize;
  final _whitesquare = SpriteSquare(
    const Size(squareSize, squareSize), 
    const Color(0xFFFFFFFF), 
    handleRemoveSelf, 
    top, // 注意参数顺序,第四个是top
    left // 第五个是left
  );
  _background.addChild(_whitesquare);
  return true;
}

内容的提问来源于stack exchange,提问作者Matt Croak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:18:02