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

5
import 'package:flutter/foundation.dart';
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
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
29
  void update(DragUpdateDetails details) {
30 31 32 33
    onUpdate(details);
  }

  @override
34
  void cancel() {
35 36 37 38
    onCancel();
  }

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

class _IgnoreDrag extends Drag {
}

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

  final MaterialPointArcTween arc;
54
  final Animation<double> _repaint;
55

56
  void drawPoint(Canvas canvas, Offset point, Color color) {
57
    final Paint paint = Paint()
58 59 60 61 62 63 64 65 66 67 68 69
      ..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) {
70
    final Paint paint = Paint();
71 72

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

    paint
76
      ..isAntiAlias = false // Work-around for github.com/flutter/flutter/issues/5720
77
      ..color = Colors.green.withOpacity(0.25)
78 79 80 81 82 83 84
      ..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);

85 86
    drawPoint(canvas, arc.begin, Colors.green);
    drawPoint(canvas, arc.end, Colors.red);
87 88

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

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

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

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

  final AnimationController controller;

  @override
110
  _PointDemoState createState() => _PointDemoState();
111 112 113
}

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

  CurvedAnimation _animation;
  _DragTarget _dragTarget;
118
  Size _screenSize;
119 120
  Offset _begin;
  Offset _end;
121 122 123 124

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

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

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

139
    final RenderBox box = _painterKey.currentContext.findRenderObject() as RenderBox;
140 141 142 143 144 145 146 147 148 149 150
    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;
    });

151
    return _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd);
152 153
  }

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

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

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

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

187 188
    final MaterialPointArcTween arc = MaterialPointArcTween(begin: _begin, end: _end);
    return RawGestureDetector(
189
      behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
190
      gestures: <Type, GestureRecognizerFactory>{
191 192
        ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
          () => ImmediateMultiDragGestureRecognizer(),
193
          (ImmediateMultiDragGestureRecognizer instance) {
194
            instance.onStart = _handleOnStart;
195 196
          },
        ),
197
      },
198 199
      child: ClipRect(
        child: CustomPaint(
200
          key: _painterKey,
201
          foregroundPainter: _PointDemoPainter(
202
            repaint: _animation,
203
            arc: arc,
204 205 206 207
          ),
          // 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.
208 209
          child: IgnorePointer(
            child: Padding(
210
              padding: const EdgeInsets.all(16.0),
211
              child: Text(
212
                'Tap the refresh button to run the animation. Drag the green '
213
                "and red points to change the animation's path.",
214 215 216 217 218 219
                style: Theme.of(context).textTheme.caption.copyWith(fontSize: 16.0),
              ),
            ),
          ),
        ),
      ),
220 221 222 223 224 225 226
    );
  }
}

class _RectangleDemoPainter extends CustomPainter {
  _RectangleDemoPainter({
    Animation<double> repaint,
227
    this.arc,
228 229 230
  }) : _repaint = repaint, super(repaint: repaint);

  final MaterialRectArcTween arc;
231
  final Animation<double> _repaint;
232

233
  void drawPoint(Canvas canvas, Offset p, Color color) {
234
    final Paint paint = Paint()
235 236 237 238 239 240 241 242 243 244 245
      ..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) {
246
    final Paint paint = Paint()
247 248 249 250 251 252 253 254 255
      ..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) {
256 257 258
    drawRect(canvas, arc.begin, Colors.green);
    drawRect(canvas, arc.end, Colors.red);
    drawRect(canvas, arc.lerp(_repaint.value), Colors.blue);
259 260 261
  }

  @override
262
  bool hitTest(Offset position) {
263 264 265 266 267 268 269 270 271
    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 {
272
  const _RectangleDemo({ Key key, this.controller }) : super(key: key);
273 274 275 276

  final AnimationController controller;

  @override
277
  _RectangleDemoState createState() => _RectangleDemoState();
278 279 280
}

class _RectangleDemoState extends State<_RectangleDemo> {
281
  final GlobalKey _painterKey = GlobalKey();
282 283 284

  CurvedAnimation _animation;
  _DragTarget _dragTarget;
285
  Size _screenSize;
286 287
  Rect _begin;
  Rect _end;
288 289 290 291

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

  @override
  void dispose() {
297
    widget.controller.value = 0.0;
298 299 300
    super.dispose();
  }

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

306
    final RenderBox box = _painterKey.currentContext.findRenderObject() as RenderBox;
307 308 309 310 311 312 313 314 315 316
    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;
    });
317
    return _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd);
318 319
  }

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

335
  void _handleDragCancel() {
336
    _dragTarget = null;
337
    widget.controller.value = 0.0;
338 339
  }

340
  void _handleDragEnd(DragEndDetails details) {
341 342 343 344 345
    _dragTarget = null;
  }

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

359 360
    final MaterialRectArcTween arc = MaterialRectArcTween(begin: _begin, end: _end);
    return RawGestureDetector(
361 362
      behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
      gestures: <Type, GestureRecognizerFactory>{
363 364
        ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
          () => ImmediateMultiDragGestureRecognizer(),
365
          (ImmediateMultiDragGestureRecognizer instance) {
366
            instance.onStart = _handleOnStart;
367 368
          },
        ),
369
      },
370 371
      child: ClipRect(
        child: CustomPaint(
372
          key: _painterKey,
373
          foregroundPainter: _RectangleDemoPainter(
374
            repaint: _animation,
375
            arc: arc,
376 377 378 379
          ),
          // 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.
380 381
          child: IgnorePointer(
            child: Padding(
382
              padding: const EdgeInsets.all(16.0),
383
              child: Text(
384
                'Tap the refresh button to run the animation. Drag the rectangles '
385
                "to change the animation's path.",
386 387 388 389 390 391
                style: Theme.of(context).textTheme.caption.copyWith(fontSize: 16.0),
              ),
            ),
          ),
        ),
      ),
392 393 394 395
    );
  }
}

396
typedef _DemoBuilder = Widget Function(_ArcDemo demo);
397 398

class _ArcDemo {
399
  _ArcDemo(this.title, this.builder, TickerProvider vsync)
400 401
    : controller = AnimationController(duration: const Duration(milliseconds: 500), vsync: vsync),
      key = GlobalKey(debugLabel: title);
402 403 404

  final String title;
  final _DemoBuilder builder;
405
  final AnimationController controller;
406 407 408 409
  final GlobalKey key;
}

class AnimationDemo extends StatefulWidget {
410
  const AnimationDemo({ Key key }) : super(key: key);
411 412

  @override
413
  _AnimationDemoState createState() => _AnimationDemoState();
414 415
}

416 417 418 419 420 421 422
class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {
  List<_ArcDemo> _allDemos;

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

438
  Future<void> _play(_ArcDemo demo) async {
439 440 441 442 443 444 445
    await demo.controller.forward();
    if (demo.key.currentState != null && demo.key.currentState.mounted)
      demo.controller.reverse();
  }

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

473
void main() {
474 475
  runApp(const MaterialApp(
    home: AnimationDemo(),
476 477
  ));
}