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

Flutter:如何在Linux(Ubuntu)中实现matrix_gesture_detector旋转功能?

问题描述

我开发一款支持手势缩放及旋转功能的应用,使用matrix_gesture_detector包时,Android端可通过双指操作完美实现缩放与旋转;但在Linux(Ubuntu 20.04)平台上,按住Ctrl、Shift、Alt键配合鼠标仅能完成缩放,无法实现旋转功能,我已参考该包的transform_demo4.dart示例代码。

解决思路与方案

Linux桌面端的键鼠手势映射和移动端双指逻辑不同,matrix_gesture_detector默认未绑定旋转对应的键鼠组合,可通过自定义手势监听来补充旋转功能:

  • 监听鼠标事件与键盘修饰键的组合,手动触发旋转逻辑
  • 在非旋转状态下保留原包的缩放功能

示例代码

class _GestureDemoState extends State<GestureDemo> {
  final _transformMatrix = Matrix4.identity();
  bool _enableRotation = false;
  Offset? _lastMousePos;

  @override
  Widget build(BuildContext context) {
    return Listener(
      // 按下鼠标时检查是否触发旋转的按键组合(这里用Shift+Alt)
      onPointerDown: (pointerEvent) {
        final pressedKeys = HardwareKeyboard.instance.logicalKeysPressed;
        _enableRotation = pressedKeys.contains(LogicalKeyboardKey.shiftLeft) && 
                          pressedKeys.contains(LogicalKeyboardKey.altLeft);
        if (_enableRotation) {
          _lastMousePos = pointerEvent.position;
        }
      },
      // 鼠标移动时计算旋转角度并更新矩阵
      onPointerMove: (pointerEvent) {
        if (_enableRotation && _lastMousePos != null) {
          // 通过鼠标横向偏移计算旋转角度,可自行调整灵敏度
          final deltaX = pointerEvent.position.dx - _lastMousePos!.dx;
          final rotateAngle = deltaX * 0.01;
          
          setState(() {
            _transformMatrix.rotateZ(rotateAngle);
          });
          _lastMousePos = pointerEvent.position;
        }
      },
      // 松开鼠标后关闭旋转状态
      onPointerUp: (_) {
        _enableRotation = false;
        _lastMousePos = null;
      },
      child: MatrixGestureDetector(
        onMatrixUpdate: (matrix, translationMatrix, scaleMatrix, rotationMatrix) {
          // 非旋转状态下应用默认的缩放变换
          if (!_enableRotation) {
            setState(() {
              _transformMatrix.multiply(matrix);
            });
          }
        },
        child: Transform(
          transform: _transformMatrix,
          child: const Center(
            child: FlutterLogo(size: 200), // 替换为你的目标组件
          ),
        ),
      ),
    );
  }
}

说明

  1. 这里选用Shift+Alt组合键触发旋转,你可根据需求修改按键组合
  2. 鼠标横向移动控制旋转角度,可调整rotateAngle的系数来改变旋转灵敏度
  3. 该方案兼容原包的缩放功能,旋转与缩放互不干扰

内容的提问来源于stack exchange,提问作者Đức Hải Trần

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:20:41