Flutter實(shí)現(xiàn)可以縮放拖拽的圖片示例代碼
前言
在pub上面找了下,沒有發(fā)現(xiàn)一個(gè)效果跟微信一樣的支持縮放拖拽效果的image,所以就自己擼了一個(gè),之前寫過Flutter 什么功能都有的Image,于是就在這個(gè)上面新增了這個(gè)功能。
主要功能:
- 縮放拖拽
- 在PageView里面縮放拖拽
支持縮放拖拽

用法
1.將extended_image的mode參數(shù)設(shè)置為ExtendedImageMode.Gesture
2.設(shè)置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 參數(shù)說明
| 參數(shù) | 描述 | 默認(rèn)值 |
|---|---|---|
| minScale | 縮放最小值 | 0.8 |
| animationMinScale | 縮放動(dòng)畫最小值,當(dāng)縮放結(jié)束時(shí)回到minScale值 | minScale * 0.8 |
| maxScale | 縮放最小值 | 5.0 |
| animationMaxScale | 縮放動(dòng)畫最大值,當(dāng)縮放結(jié)束時(shí)回到maxScale值 | maxScale * 1.2 |
| speed | 縮放拖拽速度,與用戶操作成正比 | 1.0 |
| inertialSpeed | 拖拽慣性速度,與慣性速度成正比 | 100 |
| cacheGesture | 是否緩存手勢(shì)狀態(tài),可用于Pageview中保留狀態(tài),使用clearGestureDetailsCache方法清除 | false |
| inPageView | 是否使用ExtendedImageGesturePageView展示圖片 | false |
實(shí)現(xiàn)過程
這一個(gè)功能比較簡(jiǎn)單,參考了官方的gestures demo,將縮放的Scale和Offset轉(zhuǎn)換了為了圖片最后顯示的區(qū)域,具體代碼在最后繪制圖片的時(shí)候,將gestureDetails轉(zhuǎn)換為對(duì)應(yīng)的圖片顯示區(qū)域。
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 是整個(gè)圖片在屏幕上的區(qū)域,destinationRect圖片顯示區(qū)域(會(huì)根據(jù)BoxFit的不同而所不同),通過gestureDetails的calculateFinalDestinationRect方式,計(jì)算出最終顯示區(qū)域。
讓縮放的過程看起來流暢
1.根據(jù)縮放點(diǎn)相對(duì)圖片的位置對(duì)縮放點(diǎn)作為中心點(diǎn)進(jìn)行縮放
2.如果Scale小于等于1.0的時(shí)候,按照?qǐng)D片的中心點(diǎn)進(jìn)行縮放的,而當(dāng)大于1.0并且圖片已經(jīng)鋪滿區(qū)域的時(shí)候按照1來執(zhí)行
3.當(dāng)圖片是那種長(zhǎng)寬相差很大的時(shí)候,進(jìn)行縮放的時(shí)候,將首先沿著比較長(zhǎng)的那邊進(jìn)行中心點(diǎn)縮放,直到圖片鋪滿區(qū)域之后,按照1來執(zhí)行
4.當(dāng)進(jìn)行縮放操作的時(shí)候,不進(jìn)行移動(dòng)操作
1,2,3對(duì)應(yīng)代碼
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對(duì)應(yīng)代碼,當(dāng)details.scale==1.0,說明是一個(gè)移動(dòng)操作,否則為了一個(gè)縮放操作
void _handleScaleUpdate(ScaleUpdateDetails details) {
...
var offset =
((details.scale == 1.0 ? details.focalPoint : _startingOffset) -
_normalizedOffset * scale);
...
}
獲取到了圖片的中心點(diǎn)之后,我們?cè)俑鶕?jù)Scale等到圖片的整個(gè)區(qū)域
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);
}
拖拽邊界的計(jì)算
1.計(jì)算是否需要計(jì)算限制邊界
2.如果需要將區(qū)域限制在邊界內(nèi)部
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的回彈動(dòng)畫將以最后的縮放中心點(diǎn)為中心進(jìn)行縮放,這樣縮放動(dòng)畫才看起來舒服一些
//true: user zoom/pan
//false: animation
final bool userOffset;
Offset _getCenter(Rect destinationRect) {
if (!userOffset && _center != null) {
return _center;
}
在PageView里面縮放拖拽

用法
1.使用
ExtendedImageGesturePageView展示圖片
2.設(shè)置GestureConfig的inPageView 為Ture
GestureConfig 參數(shù)說明
| 參數(shù) | 描述 | 默認(rèn)值 |
|---|---|---|
| inPageView | 是否使用ExtendedImageGesturePageView展示圖片 | false |
實(shí)現(xiàn)過程
手勢(shì)沖突
這個(gè)場(chǎng)景需要關(guān)注的是手勢(shì)的沖突問題,PageView里面是有水平或者垂直的手勢(shì)的,會(huì)跟onScaleStart/onScaleUpdate/onScaleEnd有沖突。
最開始想的是手勢(shì)應(yīng)該有冒泡,是不是可以我監(jiān)聽到了之后,不像上冒泡,這樣可以阻止PageView里面的滑動(dòng)行為,最后結(jié)論是沒有方法能阻止冒泡。
關(guān)于手勢(shì),大家可以看看拉面小姐姐關(guān)于手勢(shì)的文章,神奇的競(jìng)技場(chǎng)概念。。
既然不能阻止手勢(shì)冒泡,那么我就直接不讓你能滾動(dòng)了,然后全部的手勢(shì)都交給我,我來處理。
首先我看了下PageView關(guān)于滾動(dòng)的源碼,直接指向最終ScrollableState里面的代碼,在setCanDrag方法里面根據(jù)是否可以Drag,準(zhǔn)備了水平/垂直的手勢(shì)。
把ScrollableState里面關(guān)于水平垂直滾動(dòng)處理的代碼拿出來,我創(chuàng)建了一個(gè)屬于extended_image專門的extended_image_gesture_page_view,屬性跟PageView一樣只是沒法設(shè)置physics,
因?yàn)閺?qiáng)制設(shè)置為了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來注冊(cè)_gestureRecognizers(水平/垂直的手勢(shì))。
關(guān)于_gestureRecognizers,我之前一直好奇PageView里面有個(gè)手hold的操作是怎么做到了,直到看到源碼才知道這么個(gè)東西,源碼真是個(gè)好東西。
void _handleDragDown(DragDownDetails details) {
//print(details);
_gestureAnimation.stop();
assert(_drag == null);
assert(_hold == null);
_hold = position.hold(_disposeHold);
}
到達(dá)邊界滾動(dòng)上下一個(gè)圖片
有了之前縮放拖拽的基礎(chǔ),這部分就比較簡(jiǎn)單了。如果到達(dá)邊界就是用默認(rèn)代碼去操作PageView,否則就控制Image進(jìn)行拖拽操作
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的時(shí)候,我們需要注意下處理下慣性。
當(dāng)圖片是放大狀態(tài)而且水平或者垂直能夠滑動(dòng)的時(shí)候,我們需要_drag停止下來,以防止直接滑動(dòng)到上一個(gè)或者下一個(gè)圖片
DragEndDetails(primaryVelocity: 0.0),并且根據(jù)慣性讓圖片在范圍內(nèi)繼續(xù)慣性滑動(dòng)。
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);
}
整個(gè)extended_image的縮放和拖拽功能就介紹完畢了,再吐槽下這個(gè)手勢(shì),用起來真不舒服,希望Flutter小組有更好的方案。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Android實(shí)現(xiàn)網(wǎng)絡(luò)多線程斷點(diǎn)續(xù)傳下載功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)網(wǎng)絡(luò)多線程斷點(diǎn)續(xù)傳下載功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
Android自定義控件RatingBar調(diào)整字體大小
這篇文章主要為大家詳細(xì)介紹了Android自定義控件RatingBar調(diào)整字體大小的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
Android實(shí)現(xiàn)短信驗(yàn)證碼自動(dòng)填寫
這篇文章主要為大家詳細(xì)介紹了Android短信驗(yàn)證碼自動(dòng)填寫功能的實(shí)現(xiàn)過程,感興趣的小伙伴們可以參考一下2016-08-08
Flexbox+ReclyclerView實(shí)現(xiàn)流式布局
這篇文章主要為大家詳細(xì)介紹了Flexbox+ReclyclerView實(shí)現(xiàn)流式布局,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
Android中Permission權(quán)限機(jī)制的具體使用
這篇文章主要介紹了Android中Permission權(quán)限機(jī)制的具體使用,本文講解了權(quán)限級(jí)別 protection level、ICC(inter-component communication)權(quán)限保護(hù)等內(nèi)容,需要的朋友可以參考下2015-04-04
安卓GET與POST網(wǎng)絡(luò)請(qǐng)求的三種方式
今天小編就為大家分享一篇關(guān)于安卓GET與POST網(wǎng)絡(luò)請(qǐng)求的三種方式,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12
Android取消EditText自動(dòng)獲取默認(rèn)焦點(diǎn)
本文主要介紹了Android取消EditText自動(dòng)獲取焦點(diǎn)默認(rèn)行為的方法,具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-03-03
詳解Android中Activity運(yùn)行時(shí)屏幕方向與顯示方式
本文主要對(duì)如何控制Android中Activity運(yùn)行時(shí)屏幕方向與顯示方式進(jìn)行詳細(xì)全面的實(shí)例講解。具有很好的參考價(jià)值,需要的朋友一起來看下吧2016-12-12

