Flutter 自定義縮放控件

最近在學習 Flutter,俗話說的好,紙上得來終覺淺,因此動手擼了一個 gank.io 的 APP,有興趣的能夠 到 GitHub 看看源碼html

本文將與你們分享項目中自定義的縮放控件 GestureZoomBoxgit

pub

功能

  • 雙擊縮放。
  • 雙指縮放。
  • 以雙擊位置/雙指位置做爲縮放中心。
  • 限制縮放/拖動範圍,超過範圍自動回彈。
  • 做爲父級 Widget 直接嵌套,無侵入。

demo_big_image.gif

核心原理

手勢識別

GestureDetectorgithub

Flutter 已經提供了 GestureDetector 處理手勢(點擊、雙擊、縮放、拖動),咱們只要將可縮放內容做爲 GestureDetector 的 child 並設置相應手勢回調便可。markdown

Pan and scale callbacks cannot be used simultaneous because scale is a superset of pan. Simply use the scale callbacks instead.ide

這是源碼中的註釋,大意是「縮放是平移的超集,二者不能同時使用,只需使用縮放回調便可」。所以咱們只須要用到如下回調:svg

/// 雙擊事件回調,用來處理雙擊縮放。
final GestureTapCallback onDoubleTap;

/// 縮放值或者拖動位置發生改變。在這裏根據每次的變化量進行縮放/拖動處理。
final GestureScaleUpdateCallback onScaleUpdate;

/// 縮放/拖動結束。用來檢測並處理超過邊界的狀況。
final GestureScaleEndCallback onScaleEnd;
複製代碼

縮放和平移

使用 Transform 進行縮放和平移處理。學習

// 當前縮放值
double _scale = 1.0;

// 當前偏移值
Offset _offset = Offset.zero;

...

// 使用 Transform 包裹 child ,以便進行平移和縮放處理
Transform(
  transform: Matrix4.identity()
    ..translate(_offset.dx, _offset.dy)
    ..scale(_scale, _scale),
  child: widget.child,
  alignment: Alignment.center,
)
複製代碼

使用方法

添加依賴

dependencies:
 gesture_zoom_box: ^0.0.2
複製代碼

導包

import 'package:gesture_zoom_box/gesture_zoom_box.dart';
複製代碼

使用控件

GestureZoomBox(
    maxScale: 5.0,
    doubleTapScale: 2.0,
    duration: Duration(milliseconds: 200),
    onPressed: () => Navigator.pop(context),
    child: Image.network(widget.imageUrl),
)
複製代碼

項目地址

GitHub | Pubui

相關文章
相關標籤/搜索