ダブルタップでズーム Double Tap to Zoom
写真を2回たたくと、たたいた場所を中心に拡大し、もう一度2回たたくと元の大きさに戻る。
本物の Flutter ウィジェットが動きます(初回は数秒かかります)
どんなもの?
写真アプリや地図でおなじみの、片手で拡大できる操作です。ピンチズームと組み合わせて使います。
InteractiveViewer に TransformationController を渡し、ダブルタップで拡大後の行列(Matrix4)へアニメーションさせます。
たたいた場所が動かないように、onDoubleTapDown で位置を覚え、
「その位置 × (倍率 − 1)」だけ逆向きにずらしてから拡大するのがコツです。
すでに拡大しているときは Matrix4.identity() に戻します。
こんなときに
- 写真ビューア・地図・図面など、細部を見たいもの
避けたい場面
- ダブルタップを「いいね」など別の操作に使っている画面
最小コード
onDoubleTapDown: (d) => tapAt = d.localPosition,
onDoubleTap: () {
const s = 2.5;
final target = isZoomed
? Matrix4.identity()
: (Matrix4.identity()
..translateByDouble(-tapAt.dx * (s - 1), -tapAt.dy * (s - 1), 0, 1)
..scaleByDouble(s, s, 1, 1));
zoom = Matrix4Tween(begin: controller.value, end: target).animate(anim);
anim.forward(from: 0); // 毎フレーム controller.value = zoom.value
},
child: InteractiveViewer(transformationController: controller, child: photo),使うウィジェット
GestureDetector(onDoubleTap)InteractiveViewerTransformationControllerMatrix4Tween