前言

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

主要功能:

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

支持缩放拖拽

用法

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转换为对应的图片显示区域。

 

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里面缩放拖拽

用法

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的缩放和拖拽功能就介绍完毕了,再吐槽下这个手势,用起来真不舒服,希望Flutter小组有更好的方案。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对Devmax的支持。

Flutter实现可以缩放拖拽的图片示例代码的更多相关文章

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. Flutter中文教程-Cookbook

    Flutter中文网的Cookbook中包含了在编写Flutter应用程序时常见问题及示例。设计基础使用主题共享颜色和字体样式Images显示来自网上的图片用占位符淡入图片使用缓存图Lists创建一个基本list创建一个水平list使用长列表创建不同类型子项的List创建一个gridList处理手势处理点击添加Material触摸水波效果实现滑动关闭导航导航到新页面并返回给新页面传值从新页面返回数据给上一个页面网络从网上获取数据进行认证请求使用WebSockets

  3. android-studio – 未配置Dart SDK

    Initializinggradle…

  4. 安卓 – 从一个扑动的应用程序拨打电话

    或者有更好的选择从我的应用程序拨打电话?

  5. android – 如何在Flutter中添加Webview?

    我知道可以将WebView添加为整页,但找不到任何示例代码.我假设你可以使用PageView作为它的基础,但不知道如何调用本机androidWebView并将其添加到PageView.谁能指出我正确的方向?

  6. android – 如何将消息从Flutter传递给Native?

    如果需要与特定的API/硬件组件进行交互,您如何将Flutter的信息传递回Android/Native代码?是否有任何事件频道可以通过其他方式发送信息或类似于回调?

  7. android – 如何在Flutter App中处理onPause / onResume?

    我是否过于复杂的事情?即使我的用例似乎不需要它,我仍然想知道:如何自己处理onPause/onResume事件?

  8. android – 如何使用Flutter构建Augment Reality应用程序?

    我对Android开发有一些基础知识.最近听说过Flutter并且非常有兴趣研究它.我想知道是否有可能使用颤振构建增强现实应用程序以及要实现此目的的方法?请帮忙.解决方法截至目前,颤振不支持3D.Flutter现在专注于2D,团队长期计划为颤振提供优化的3Dapi.你读了常见问题here.

  9. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  10. Flutter StreamBuilder实现局部刷新实例详解

    这篇文章主要为大家介绍了Flutter StreamBuilder实现局部刷新实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部