Flutter使用GestureDetector工具实现手势缩放效果

GestureDetector是Flutter内部处理用户手势操作的一个小工具。

如果想要实现缩放效果需要利用到其中两个方法

onScaleStart :当用户触碰屏幕并开始缩放的时候

onScaleUpdate:当用户正在执行缩放时候

ScaleUpdateDetails 是作为函数参数进行传递的,它有以下属性

1、scale 表示上一帧的缩放比例

2、focalPoint 缩放手势中心点坐标

3、pointerCount 当前触控点数量(小于一个点说明没有用手势缩放)

这里主要用到scale这个参数。

示例:

Dart 复制代码
class ScalePage extends StatefulWidget {
  const ScalePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return GestureDetectorPageTest();
  }
}

class GestureDetectorPageTest extends State<ScalePage> {
  double _scale = 1.0;
  double _startScale = 1.0;
  bool ifScale = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("手势处理工具GestureDetector"),
      ),
      body: Container(
        color: Colors.amber,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: GestureDetector(
          child: Transform.scale(
            scale: _scale,
            child: const Image(image: AssetImage('images/a.png')),
          ),
          onScaleStart: (e) {
            _startScale = _scale;
          },
          onScaleUpdate: (e) {
            setState(() {
              _scale = _startScale * e.scale;
                //clamp 表示缩放最大不超过原图的两倍,最小不小于原图的0.5倍
              _scale = _scale.clamp(0.5, 2.0);
            });
          },
          onScaleEnd: (e) {

          },
          onDoubleTap: () {
            setState(() {
              if (ifScale) {
                _scale = _startScale * 2;
              } else {
                _scale = _startScale / 2;
              }
              _scale = _scale.clamp(0.5, 2.0);
              ifScale = !ifScale;
            });
          },
        ),
      ),
    );
  }
}
相关推荐
君赏3 天前
棉宇宙 Flutter 热更新是如何落地的
flutter
恋猫de小郭3 天前
AndroidX 新增 Security State ,支持可编程的系统安全状态查询
android·前端·flutter
zihan5183 天前
自己做软件日记9/21 得到了一个良好的文件结构框架
后端·flutter·前端框架·android studio
ZFJ_张福杰4 天前
【Flutter】Flutter 中有哪些耗时操作?从 UI 卡顿到 Isolate 性能优化
flutter·性能优化·卡顿·isolate
sakiko_4 天前
Flutter:Dart学习笔记1:基础UI组件等
flutter
9765033354 天前
iOS 上架 4.3a 被拒【uniapp专讲】
flutter·ios·objective-c·uniapp·swift
传奇开心果编程5 天前
【Flutter入门练中学】第2课:布局系统
学习·flutter·ui
君赏5 天前
FlutterPatch:把 Shorebird 热更新的控制面搬回自己服务器
flutter
用户2181697049305 天前
Flutter tootip 轻量级提示
flutter
用户2181697049305 天前
Flutter 拖拽 Draggable DragTarget
flutter