Flutter InteractiveViewer 支持平移和缩放子Widget

1,081

在码农的世界里,优美的应用体验,来源于程序员对细节的处理以及自我要求的境界,年轻人也是忙忙碌碌的码农中一员,每天、每周,都会留下一些脚印,就是这些创作的内容,有一种执着,就是不知为什么,如果你迷茫,不妨来瞅瞅码农的轨迹。


1 InteractiveViewer 是什么 ?

InteractiveViewer 是Flutter 中一个可以将子Widget进行平移与缩放操作的 Widget,用户可以通过拖动进行平移或者双指捏放来放大来子元素。

2 基本使用

如对一个图片的双指捍合放大

void main() => runApp(MaterialApp(
      home: TestPage(),
    ));

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      ///填充布局
      body: Center(
        child: InteractiveViewer(
          alignPanAxis: false,
          //对子Widget 进行缩放平移
          child: Image.asset("assets/images/banner1.webp"),
        ),
      ),
    );
  }
}

3 InteractiveViewer 属性详细说明

  InteractiveViewer({
    Key? key,
    this.alignPanAxis = false,
    this.boundaryMargin = EdgeInsets.zero,
    this.constrained = true,
    // These default scale values were eyeballed as reasonable limits for common
    // use cases.
    this.maxScale = 2.5,
    this.minScale = 0.8,
    this.onInteractionEnd,
    this.onInteractionStart,
    this.onInteractionUpdate,
    this.panEnabled = true,
    this.scaleEnabled = true,
    this.transformationController,
    required this.child,
  })

maxScale属性用来设置最大缩放比例,minScale用来设置最小缩放比例。

3.1 alignPanAxis

默认为 false ,子Widget可以沿任意方向平移,如果设置为true,对角线平移是不允许的,也就是说只能沿一个方向平移,如果开始平移为水平方向则在本次手指抬起前只能是水平移动,竖直方向的移动同理。

3.2 boundaryMargin

平移边缘距离,默认为EdgeInsets.zero,四个边缘为0,如下图平移无边缘出现 在这里插入图片描述 当配置为 EdgeInsets.all(20) 时,效果如下图所示:

在这里插入图片描述

3.3 constrained 属性

用来设置 是否约束子 Widget ,默认为true,也就是 InteractiveViewer 的大小会强加给子Widget的大小约束,如果设置为 false ,则可理解为是 InteractiveViewer 包裹子Widget.

3.4 InteractiveViewer 手势监听与回调

InteractiveViewer(
   //对子Widget 进行缩放平移
   child: Image.asset("assets/images/banner1.webp"),
   //结束平移与缩放的回调
   onInteractionEnd: (ScaleEndDetails details) {},
   //开始平移与缩放的回调
   onInteractionStart: (ScaleStartDetails details) {},
   //平移或者是缩放过程中的回调
   onInteractionUpdate: (ScaleUpdateDetails details) {},
 )

完毕