Flutter 能夠縮放拖拽的圖片

extended_image 相關文章git

pub package
在pub上面找了下,沒有發現一個效果跟微信同樣的支持縮放拖拽效果的image,因此就本身擼了一個,以前寫過 Flutter 什麼功能都有的Image,因而就在這個上面新增了這個功能。

主要功能:github

  • 縮放拖拽
  • 在PageView裏面縮放拖拽

支持縮放拖拽

用法

1.將extended_image的mode參數設置爲ExtendedImageMode.Gesturecanvas

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轉換爲對應的圖片顯示區域。markdown

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方式,計算出最終顯示區域。app

讓縮放的過程看起來流暢

1.根據縮放點相對圖片的位置對縮放點做爲中心點進行縮放編輯器

2.若是Scale小於等於1.0的時候,按照圖片的中心點進行縮放的,而當大於1.0而且圖片已經鋪滿區域的時候按照1來執行ide

3.當圖片是那種長寬相差很大的時候,進行縮放的時候,將首先沿着比較長的那邊進行中心點縮放,直到圖片鋪滿區域以後,按照1來執行svg

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裏面縮放拖拽

用法

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.totalScale > 1.0 &&
          (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 的縮放和拖拽功能就介紹完畢了,再吐槽下這個手勢,用起來真不舒服,但願Flutter小組有更好的方案。

pub package
最後放上 extended_image,若是你有什麼不明白或者對這個方案有什麼改進的地方,請告訴我,歡迎加入 Flutter Candies,一塊兒生產可愛的Flutter 小糖果(QQ羣:181398081)

相關文章
相關標籤/搜索