Flutter 可以缩放拖拽的图片

在pub上面找了下,没有发现一个作用跟微信相同的支撑缩放拖拽作用的image,所以就自己撸了一个,之前写过Flutter 什么功用都有的Image,于是就在这个上面新增了这个功用。

主要功用:

  • 缩放拖拽
  • 在PageView里边缩放拖拽

支撑缩放拖拽

Flutter 可以缩放拖拽的图片

image

用法

1.将extended_image的mode参数设置为ExtendedImageMode.Gesture

2.设置GestureConfig

 ExtendedImage.network(
          imageTestUrl,
          fit: BoxFit.contain,
          //enableLoadState: false,
          mode: ExtendedImageMode.Gesture,
          gestureConfig: GestureConfig(
              minScale: 0.9,
              animationMinScale: 0.7,
              maxScale: 3.0,
              animationMaxScale: 3.5,
              speed: 1.0,
              inertialSpeed: 100.0,
              initialScale: 1.0,
              inPageView: false),
        )

GestureConfig 参数阐明

参数 描绘 默认值
minScale 缩放最小值 0.8
animationMinScale 缩放动画最小值,当缩放结束时回到minScale值 minScale * 0.8
maxScale 缩放最小值 5.0
animationMaxScale 缩放动画最大值,当缩放结束时回到maxScale值 maxScale * 1.2
speed 缩放拖拽速度,与用户操作成正比 1.0
inertialSpeed 拖拽惯性速度,与惯性速度成正比 100
cacheGesture 是否缓存手势状况,可用于Pageview中保留状况,使用clearGestureDetailsCache办法铲除 false
inPageView 是否使用ExtendedImageGesturePageView展现图片 false

完成进程

这一个功用比较简单,参阅了官方的gestures demo,将缩放的Scale和Offset转换了为了图片终究显现的区域,具体代码在终究制作图片的时分,将gestureDetails转换为对应的图片显现区域。

Flutter 可以缩放拖拽的图片

image

 bool gestureClip = false;
  if (gestureDetails != null) {
    destinationRect =
        gestureDetails.calculateFinalDestinationRect(rect, destinationRect);
    ///outside and need clip
    gestureClip = outRect(rect, destinationRect);
    if (gestureClip) {
      canvas.save();
      canvas.clipRect(rect);
    }
  }

rect 是整个图片在屏幕上的区域,destinationRect图片显现区域(会依据BoxFit的不同而所不同),经过gestureDetails的calculateFinalDestinationRect方式,核算出终究显现区域。

让缩放的进程看起来流通

1.依据缩放点相对图片的位置对缩放点作为中心点进行缩放

2.假如Scale小于等于1.0的时分,依照图片的中心点进行缩放的,而当大于1.0并且图片已经铺满区域的时分依照1来履行

3.当图片是那种长宽相差很大的时分,进行缩放的时分,将首先沿着比较长的那儿进行中心点缩放,直到图片铺满区域之后,依照1来履行

4.当进行缩放操作的时分,不进行移动操作

1,2,3对应代码

Offset _getCenter(Rect destinationRect) {
    if (!userOffset && _center != null) {
      return _center;
    }
    if (totalScale > 1.0) {
      if (_computeHorizontalBoundary && _computeVerticalBoundary) {
        return destinationRect.center * totalScale + offset;
      } else if (_computeHorizontalBoundary) {
        //only scale Horizontal
        return Offset(destinationRect.center.dx * totalScale,
                destinationRect.center.dy) +
            Offset(offset.dx, 0.0);
      } else if (_computeVerticalBoundary) {
        //only scale Vertical
        return Offset(destinationRect.center.dx,
                destinationRect.center.dy * totalScale) +
            Offset(0.0, offset.dy);
      } else {
        return destinationRect.center;
      }
    } else {
      return destinationRect.center;
    }
  }

4对应代码,当details.scale==1.0,阐明是一个移动操作,不然为了一个缩放操作

void _handleScaleUpdate(ScaleUpdateDetails details) {
    ...
    var offset =
        ((details.scale == 1.0 ? details.focalPoint : _startingOffset) -
            _normalizedOffset * scale);
    ...
  }

获取到了图片的中心点之后,咱们再依据Scale等到图片的整个区域

 Rect _getDestinationRect(Rect destinationRect, Offset center) {
    final double width = destinationRect.width * totalScale;
    final double height = destinationRect.height * totalScale;
    return Rect.fromLTWH(
        center.dx - width / 2.0, center.dy - height / 2.0, width, height);
  }

拖拽鸿沟的核算

1.核算是否需求核算限制鸿沟 2.假如需求将区域限制在鸿沟内部

    if (_computeHorizontalBoundary) {
      //move right
      if (result.left >= layoutRect.left) {
        result = Rect.fromLTWH(0.0, result.top, result.width, result.height);
        _boundary.left = true;
      }
      ///move left
      if (result.right <= layoutRect.right) {
        result = Rect.fromLTWH(layoutRect.right - result.width, result.top,
            result.width, result.height);
        _boundary.right = true;
      }
    }
    if (_computeVerticalBoundary) {
      //move down
      if (result.bottom <= layoutRect.bottom) {
        result = Rect.fromLTWH(result.left, layoutRect.bottom - result.height,
            result.width, result.height);
        _boundary.bottom = true;
      }
      //move up
      if (result.top >= layoutRect.top) {
        result = Rect.fromLTWH(
            result.left, layoutRect.top, result.width, result.height);
        _boundary.top = true;
      }
    }
    _computeHorizontalBoundary =
        result.left <= layoutRect.left && result.right >= layoutRect.right;
    _computeVerticalBoundary =
        result.top <= layoutRect.top && result.bottom >= layoutRect.bottom;

缩放回弹作用以及拖拽惯性作用

void _handleScaleEnd(ScaleEndDetails details) {
    //animate back to maxScale if gesture exceeded the maxScale specified
    if (_gestureDetails.totalScale > _gestureConfig.maxScale) {
      final double velocity =
          (_gestureDetails.totalScale - _gestureConfig.maxScale) /
              _gestureConfig.maxScale;
      _gestureAnimation.animationScale(
          _gestureDetails.totalScale, _gestureConfig.maxScale, velocity);
      return;
    }
    //animate back to minScale if gesture fell smaller than the minScale specified
    if (_gestureDetails.totalScale < _gestureConfig.minScale) {
      final double velocity =
          (_gestureConfig.minScale - _gestureDetails.totalScale) /
              _gestureConfig.minScale;
      _gestureAnimation.animationScale(
          _gestureDetails.totalScale, _gestureConfig.minScale, velocity);
      return;
    }
    if (_gestureDetails.gestureState == GestureState.pan) {
      // get magnitude from gesture velocity
      final double magnitude = details.velocity.pixelsPerSecond.distance;
      // do a significant magnitude
      if (magnitude >= minMagnitude) {
        final Offset direction = details.velocity.pixelsPerSecond /
            magnitude *
            _gestureConfig.inertialSpeed;
        _gestureAnimation.animationOffset(
            _gestureDetails.offset, _gestureDetails.offset + direction);
      }
    }
  }

唯一留意的是Scale的回弹动画将以终究的缩放中心点为中心进行缩放,这样缩放动画才看起来舒服一些

  //true: user zoom/pan
  //false: animation
  final bool userOffset;
  Offset _getCenter(Rect destinationRect) {
    if (!userOffset && _center != null) {
      return _center;
    }

在PageView里边缩放拖拽

Flutter 可以缩放拖拽的图片

image

用法

1.使用 ExtendedImageGesturePageView展现图片

2.设置GestureConfig的inPageView 为Ture

GestureConfig 参数阐明

参数 描绘 默认值
inPageView 是否使用ExtendedImageGesturePageView展现图片 false

完成进程

手势抵触

这个场景需求关注的是手势的抵触问题,PageView里边是有水平或许笔直的手势的,会跟onScaleStart/onScaleUpdate/onScaleEnd有抵触。

最开端想的是手势应该有冒泡,是不是能够我监听到了之后,不像上冒泡,这样能够阻挠PageView里边的滑动行为,终究结论是没有办法能阻挠冒泡。

关于手势,咱们能够看看拉面小姐姐关于手势的文章,奇特的竞技场概念。。

已然不能阻挠手势冒泡,那么我就直接不让你能翻滚了,然后悉数的手势都交给我,我来处理。

首先我看了下PageView关于翻滚的源码,直接指向终究ScrollableState里边的代码,在setCanDrag办法里边依据是否能够Drag,准备了水平/笔直的手势。

把ScrollableState里边关于水平笔直翻滚处理的代码拿出来,我创建了一个归于extended_image专门的extended_image_gesture_page_view,特点跟PageView相同仅仅没法设置physics, 由于强制设置为了NeverScrollableScrollPhysics

    Widget result = PageView.custom(
      scrollDirection: widget.scrollDirection,
      reverse: widget.reverse,
      controller: widget.controller,
      childrenDelegate: widget.childrenDelegate,
      pageSnapping: widget.pageSnapping,
      physics: widget.physics,
      onPageChanged: widget.onPageChanged,
      key: widget.key,
    );
    result = RawGestureDetector(
      gestures: _gestureRecognizers,
      behavior: HitTestBehavior.opaque,
      child: result,
    );

然后咱们经过RawGestureDetector来注册_gestureRecognizers(水平/笔直的手势)。

关于_gestureRecognizers,我之前一直猎奇PageView里边有个手hold的操作是怎么做到了,直到看到源码才知道这么个东西,源码真是个好东西。

 void _handleDragDown(DragDownDetails details) {
    //print(details);
    _gestureAnimation.stop();
    assert(_drag == null);
    assert(_hold == null);
    _hold = position.hold(_disposeHold);
  }

抵达鸿沟翻滚上下一个图片

有了之前缩放拖拽的基础,这部分就比较简单了。假如抵达鸿沟便是用默认代码去操作PageView,不然就操控Image进行拖拽操作

void _handleDragUpdate(DragUpdateDetails details) {
    // _drag might be null if the drag activity ended and called _disposeDrag.
    assert(_hold == null || _drag == null);
    var delta = details.delta;
    if (extendedImageGestureState != null) {
      var gestureDetails = extendedImageGestureState.gestureDetails;
      if (gestureDetails != null) {
        if (gestureDetails.movePage(delta)) {
          _drag?.update(details);
        } else {
          extendedImageGestureState.gestureDetails = GestureDetails(
              offset: gestureDetails.offset +
                  delta * extendedImageGestureState.imageGestureConfig.speed,
              totalScale: gestureDetails.totalScale,
              gestureDetails: gestureDetails);
        }
      } else {
        _drag?.update(details);
      }
    } else {
      _drag?.update(details);
    }
  }

拖拽惯性作用

在DragEnd的时分,咱们需求留意下处理下惯性。 当图片是扩大状况而且水平或许笔直能够滑动的时分,咱们需求_drag停止下来,以避免直接滑动到上一个或许下一个图片 DragEndDetails(primaryVelocity: 0.0),并且依据惯性让图片在范围内持续惯性滑动。

void _handleDragEnd(DragEndDetails details) {
    // _drag might be null if the drag activity ended and called _disposeDrag.
    assert(_hold == null || _drag == null);
    var temp = details;
    if (extendedImageGestureState != null) {
      var gestureDetails = extendedImageGestureState.gestureDetails;
      if (gestureDetails != null && gestureDetails.computeHorizontalBoundary ||
          gestureDetails.computeVerticalBoundary) {
        //stop
        temp = DragEndDetails(primaryVelocity: 0.0);
        // get magnitude from gesture velocity
        final double magnitude = details.velocity.pixelsPerSecond.distance;
        // do a significant magnitude
        if (magnitude >= minMagnitude) {
          Offset direction = details.velocity.pixelsPerSecond /
              magnitude *
              (extendedImageGestureState.imageGestureConfig.inertialSpeed);
          if (widget.scrollDirection == Axis.horizontal) {
            direction = Offset(direction.dx, 0.0);
          } else {
            direction = Offset(0.0, direction.dy);
          }
          _gestureAnimation.animationOffset(
              gestureDetails.offset, gestureDetails.offset + direction);
        }
      }
    }
    _drag?.end(temp);
    assert(_drag == null);
  }

整个extended_image的缩放和拖拽功用就介绍结束了