material_arc.dart 13.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import 'package:flutter/foundation.dart';
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

enum _DragTarget {
  start,
  end
}

// How close a drag's start position must be to the target point. This is
// a distance squared.
const double _kTargetSlop = 2500.0;

// Used by the Painter classes.
const double _kPointRadius = 6.0;

class _DragHandler extends Drag {
  _DragHandler(this.onUpdate, this.onCancel, this.onEnd);

  final GestureDragUpdateCallback onUpdate;
  final GestureDragCancelCallback onCancel;
  final GestureDragEndCallback onEnd;

  @override
31
  void update(DragUpdateDetails details) {
32 33 34 35
    onUpdate(details);
  }

  @override
36
  void cancel() {
37 38 39 40
    onCancel();
  }

  @override
41
  void end(DragEndDetails details) {
42 43 44 45 46 47 48 49 50 51
    onEnd(details);
  }
}

class _IgnoreDrag extends Drag {
}

class _PointDemoPainter extends CustomPainter {
  _PointDemoPainter({
    Animation<double> repaint,
52
    this.arc,
53 54 55
  }) : _repaint = repaint, super(repaint: repaint);

  final MaterialPointArcTween arc;
56
  final Animation<double> _repaint;
57

58
  void drawPoint(Canvas canvas, Offset point, Color color) {
59
    final Paint paint = Paint()
60 61 62 63 64 65 66 67 68 69 70 71
      ..color = color.withOpacity(0.25)
      ..style = PaintingStyle.fill;
    canvas.drawCircle(point, _kPointRadius, paint);
    paint
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawCircle(point, _kPointRadius + 1.0, paint);
  }

  @override
  void paint(Canvas canvas, Size size) {
72
    final Paint paint = Paint();
73 74

    if (arc.center != null)
75
      drawPoint(canvas, arc.center, Colors.grey.shade400);
76 77

    paint
78
      ..isAntiAlias = false // Work-around for github.com/flutter/flutter/issues/5720
79
      ..color = Colors.green.withOpacity(0.25)
80 81 82 83 84 85 86
      ..strokeWidth = 4.0
      ..style = PaintingStyle.stroke;
    if (arc.center != null && arc.radius != null)
      canvas.drawCircle(arc.center, arc.radius, paint);
    else
      canvas.drawLine(arc.begin, arc.end, paint);

87 88
    drawPoint(canvas, arc.begin, Colors.green);
    drawPoint(canvas, arc.end, Colors.red);
89 90

    paint
91
      ..color = Colors.green
92 93 94 95 96
      ..style = PaintingStyle.fill;
    canvas.drawCircle(arc.lerp(_repaint.value), _kPointRadius, paint);
  }

  @override
97
  bool hitTest(Offset position) {
98 99 100 101 102 103 104 105 106
    return (arc.begin - position).distanceSquared < _kTargetSlop
        || (arc.end - position).distanceSquared < _kTargetSlop;
  }

  @override
  bool shouldRepaint(_PointDemoPainter oldPainter) => arc != oldPainter.arc;
}

class _PointDemo extends StatefulWidget {
107
  const _PointDemo({ Key key, this.controller }) : super(key: key);
108 109 110 111

  final AnimationController controller;

  @override
112
  _PointDemoState createState() => _PointDemoState();
113 114 115
}

class _PointDemoState extends State<_PointDemo> {
116
  final GlobalKey _painterKey = GlobalKey();
117 118 119

  CurvedAnimation _animation;
  _DragTarget _dragTarget;
120
  Size _screenSize;
121 122
  Offset _begin;
  Offset _end;
123 124 125 126

  @override
  void initState() {
    super.initState();
127
    _animation = CurvedAnimation(parent: widget.controller, curve: Curves.fastOutSlowIn);
128 129 130 131
  }

  @override
  void dispose() {
132
    widget.controller.value = 0.0;
133 134 135
    super.dispose();
  }

136
  Drag _handleOnStart(Offset position) {
137 138
    // TODO(hansmuller): allow the user to drag both points at the same time.
    if (_dragTarget != null)
139
      return _IgnoreDrag();
140

141
    final RenderBox box = _painterKey.currentContext.findRenderObject() as RenderBox;
142 143 144 145 146 147 148 149 150 151 152
    final double startOffset = (box.localToGlobal(_begin) - position).distanceSquared;
    final double endOffset = (box.localToGlobal(_end) - position).distanceSquared;
    setState(() {
      if (startOffset < endOffset && startOffset < _kTargetSlop)
        _dragTarget = _DragTarget.start;
      else if (endOffset < _kTargetSlop)
        _dragTarget = _DragTarget.end;
      else
        _dragTarget = null;
    });

153
    return _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd);
154 155
  }

156
  void _handleDragUpdate(DragUpdateDetails details) {
157 158 159 160 161 162 163 164 165 166 167 168 169 170
    switch (_dragTarget) {
      case _DragTarget.start:
        setState(() {
          _begin = _begin + details.delta;
        });
        break;
      case _DragTarget.end:
        setState(() {
          _end = _end + details.delta;
        });
        break;
    }
  }

171
  void _handleDragCancel() {
172
    _dragTarget = null;
173
    widget.controller.value = 0.0;
174 175
  }

176
  void _handleDragEnd(DragEndDetails details) {
177 178 179 180 181
    _dragTarget = null;
  }

  @override
  Widget build(BuildContext context) {
182
    final Size screenSize = MediaQuery.of(context).size;
183 184
    if (_screenSize == null || _screenSize != screenSize) {
      _screenSize = screenSize;
185 186
      _begin = Offset(screenSize.width * 0.5, screenSize.height * 0.2);
      _end = Offset(screenSize.width * 0.1, screenSize.height * 0.4);
187
    }
188

189 190
    final MaterialPointArcTween arc = MaterialPointArcTween(begin: _begin, end: _end);
    return RawGestureDetector(
191
      behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
192
      gestures: <Type, GestureRecognizerFactory>{
193 194
        ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
          () => ImmediateMultiDragGestureRecognizer(),
195 196 197 198 199
          (ImmediateMultiDragGestureRecognizer instance) {
            instance
              ..onStart = _handleOnStart;
          },
        ),
200
      },
201 202
      child: ClipRect(
        child: CustomPaint(
203
          key: _painterKey,
204
          foregroundPainter: _PointDemoPainter(
205
            repaint: _animation,
206
            arc: arc,
207 208 209 210
          ),
          // Watch out: if this IgnorePointer is left out, then gestures that
          // fail _PointDemoPainter.hitTest() will still be recognized because
          // they do overlap this child, which is as big as the CustomPaint.
211 212
          child: IgnorePointer(
            child: Padding(
213
              padding: const EdgeInsets.all(16.0),
214
              child: Text(
215
                'Tap the refresh button to run the animation. Drag the green '
216
                "and red points to change the animation's path.",
217 218 219 220 221 222
                style: Theme.of(context).textTheme.caption.copyWith(fontSize: 16.0),
              ),
            ),
          ),
        ),
      ),
223 224 225 226 227 228 229
    );
  }
}

class _RectangleDemoPainter extends CustomPainter {
  _RectangleDemoPainter({
    Animation<double> repaint,
230
    this.arc,
231 232 233
  }) : _repaint = repaint, super(repaint: repaint);

  final MaterialRectArcTween arc;
234
  final Animation<double> _repaint;
235

236
  void drawPoint(Canvas canvas, Offset p, Color color) {
237
    final Paint paint = Paint()
238 239 240 241 242 243 244 245 246 247 248
      ..color = color.withOpacity(0.25)
      ..style = PaintingStyle.fill;
    canvas.drawCircle(p, _kPointRadius, paint);
    paint
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawCircle(p, _kPointRadius + 1.0, paint);
  }

  void drawRect(Canvas canvas, Rect rect, Color color) {
249
    final Paint paint = Paint()
250 251 252 253 254 255 256 257 258
      ..color = color.withOpacity(0.25)
      ..strokeWidth = 4.0
      ..style = PaintingStyle.stroke;
    canvas.drawRect(rect, paint);
    drawPoint(canvas, rect.center, color);
  }

  @override
  void paint(Canvas canvas, Size size) {
259 260 261
    drawRect(canvas, arc.begin, Colors.green);
    drawRect(canvas, arc.end, Colors.red);
    drawRect(canvas, arc.lerp(_repaint.value), Colors.blue);
262 263 264
  }

  @override
265
  bool hitTest(Offset position) {
266 267 268 269 270 271 272 273 274
    return (arc.begin.center - position).distanceSquared < _kTargetSlop
        || (arc.end.center - position).distanceSquared < _kTargetSlop;
  }

  @override
  bool shouldRepaint(_RectangleDemoPainter oldPainter) => arc != oldPainter.arc;
}

class _RectangleDemo extends StatefulWidget {
275
  const _RectangleDemo({ Key key, this.controller }) : super(key: key);
276 277 278 279

  final AnimationController controller;

  @override
280
  _RectangleDemoState createState() => _RectangleDemoState();
281 282 283
}

class _RectangleDemoState extends State<_RectangleDemo> {
284
  final GlobalKey _painterKey = GlobalKey();
285 286 287

  CurvedAnimation _animation;
  _DragTarget _dragTarget;
288
  Size _screenSize;
289 290
  Rect _begin;
  Rect _end;
291 292 293 294

  @override
  void initState() {
    super.initState();
295
    _animation = CurvedAnimation(parent: widget.controller, curve: Curves.fastOutSlowIn);
296 297 298 299
  }

  @override
  void dispose() {
300
    widget.controller.value = 0.0;
301 302 303
    super.dispose();
  }

304
  Drag _handleOnStart(Offset position) {
305 306
    // TODO(hansmuller): allow the user to drag both points at the same time.
    if (_dragTarget != null)
307
      return _IgnoreDrag();
308

309
    final RenderBox box = _painterKey.currentContext.findRenderObject() as RenderBox;
310 311 312 313 314 315 316 317 318 319
    final double startOffset = (box.localToGlobal(_begin.center) - position).distanceSquared;
    final double endOffset = (box.localToGlobal(_end.center) - position).distanceSquared;
    setState(() {
      if (startOffset < endOffset && startOffset < _kTargetSlop)
        _dragTarget = _DragTarget.start;
      else if (endOffset < _kTargetSlop)
        _dragTarget = _DragTarget.end;
      else
        _dragTarget = null;
    });
320
    return _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd);
321 322
  }

323
  void _handleDragUpdate(DragUpdateDetails details) {
324 325 326 327 328 329 330 331 332 333 334 335 336 337
    switch (_dragTarget) {
      case _DragTarget.start:
        setState(() {
          _begin = _begin.shift(details.delta);
        });
        break;
      case _DragTarget.end:
        setState(() {
          _end = _end.shift(details.delta);
        });
        break;
    }
  }

338
  void _handleDragCancel() {
339
    _dragTarget = null;
340
    widget.controller.value = 0.0;
341 342
  }

343
  void _handleDragEnd(DragEndDetails details) {
344 345 346 347 348
    _dragTarget = null;
  }

  @override
  Widget build(BuildContext context) {
349
    final Size screenSize = MediaQuery.of(context).size;
350 351
    if (_screenSize == null || _screenSize != screenSize) {
      _screenSize = screenSize;
352
      _begin = Rect.fromLTWH(
353
        screenSize.width * 0.5, screenSize.height * 0.2,
354
        screenSize.width * 0.4, screenSize.height * 0.2,
355
      );
356
      _end = Rect.fromLTWH(
357
        screenSize.width * 0.1, screenSize.height * 0.4,
358
        screenSize.width * 0.3, screenSize.height * 0.3,
359 360
      );
    }
361

362 363
    final MaterialRectArcTween arc = MaterialRectArcTween(begin: _begin, end: _end);
    return RawGestureDetector(
364 365
      behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
      gestures: <Type, GestureRecognizerFactory>{
366 367
        ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
          () => ImmediateMultiDragGestureRecognizer(),
368 369 370 371 372
          (ImmediateMultiDragGestureRecognizer instance) {
            instance
              ..onStart = _handleOnStart;
          },
        ),
373
      },
374 375
      child: ClipRect(
        child: CustomPaint(
376
          key: _painterKey,
377
          foregroundPainter: _RectangleDemoPainter(
378
            repaint: _animation,
379
            arc: arc,
380 381 382 383
          ),
          // Watch out: if this IgnorePointer is left out, then gestures that
          // fail _RectDemoPainter.hitTest() will still be recognized because
          // they do overlap this child, which is as big as the CustomPaint.
384 385
          child: IgnorePointer(
            child: Padding(
386
              padding: const EdgeInsets.all(16.0),
387
              child: Text(
388
                'Tap the refresh button to run the animation. Drag the rectangles '
389
                "to change the animation's path.",
390 391 392 393 394 395
                style: Theme.of(context).textTheme.caption.copyWith(fontSize: 16.0),
              ),
            ),
          ),
        ),
      ),
396 397 398 399
    );
  }
}

400
typedef _DemoBuilder = Widget Function(_ArcDemo demo);
401 402

class _ArcDemo {
403
  _ArcDemo(this.title, this.builder, TickerProvider vsync)
404 405
    : controller = AnimationController(duration: const Duration(milliseconds: 500), vsync: vsync),
      key = GlobalKey(debugLabel: title);
406 407 408

  final String title;
  final _DemoBuilder builder;
409
  final AnimationController controller;
410 411 412 413
  final GlobalKey key;
}

class AnimationDemo extends StatefulWidget {
414
  const AnimationDemo({ Key key }) : super(key: key);
415 416

  @override
417
  _AnimationDemoState createState() => _AnimationDemoState();
418 419
}

420 421 422 423 424 425 426
class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {
  List<_ArcDemo> _allDemos;

  @override
  void initState() {
    super.initState();
    _allDemos = <_ArcDemo>[
427 428
      _ArcDemo('POINT', (_ArcDemo demo) {
        return _PointDemo(
429
          key: demo.key,
430
          controller: demo.controller,
431 432
        );
      }, this),
433 434
      _ArcDemo('RECTANGLE', (_ArcDemo demo) {
        return _RectangleDemo(
435
          key: demo.key,
436
          controller: demo.controller,
437 438 439 440
        );
      }, this),
    ];
  }
441

442
  Future<void> _play(_ArcDemo demo) async {
443 444 445 446 447 448 449
    await demo.controller.forward();
    if (demo.key.currentState != null && demo.key.currentState.mounted)
      demo.controller.reverse();
  }

  @override
  Widget build(BuildContext context) {
450
    return DefaultTabController(
Hans Muller's avatar
Hans Muller committed
451
      length: _allDemos.length,
452 453
      child: Scaffold(
        appBar: AppBar(
454
          title: const Text('Animation'),
455
          bottom: TabBar(
456
            tabs: _allDemos.map<Tab>((_ArcDemo demo) => Tab(text: demo.title)).toList(),
Hans Muller's avatar
Hans Muller committed
457
          ),
458
        ),
459
        floatingActionButton: Builder(
Hans Muller's avatar
Hans Muller committed
460
          builder: (BuildContext context) {
461
            return FloatingActionButton(
462
              child: const Icon(Icons.refresh),
Hans Muller's avatar
Hans Muller committed
463 464 465 466 467
              onPressed: () {
                _play(_allDemos[DefaultTabController.of(context).index]);
              },
            );
          },
468
        ),
469
        body: TabBarView(
470 471 472
          children: _allDemos.map<Widget>((_ArcDemo demo) => demo.builder(demo)).toList(),
        ),
      ),
473 474 475
    );
  }
}
476

477
void main() {
478 479
  runApp(const MaterialApp(
    home: AnimationDemo(),
480 481
  ));
}