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

import 'dart:math' as math;
6
import 'dart:ui' show lerpDouble;
7

8
import 'package:flutter/animation.dart';
9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/painting.dart';
11 12 13 14 15

// How close the begin and end points must be to an axis to be considered
// vertical or horizontal.
const double _kOnAxisDelta = 2.0;

16 17 18 19 20
/// A [Tween] that interpolates an [Offset] along a circular arc.
///
/// This class specializes the interpolation of [Tween<Offset>] so that instead
/// of a straight line, the intermediate points follow the arc of a circle in a
/// manner consistent with material design principles.
21 22 23 24 25 26 27 28 29
///
/// The arc's radius is related to the bounding box that contains the [begin]
/// and [end] points. If the bounding box is taller than it is wide, then the
/// center of the circle will be horizontally aligned with the end point.
/// Otherwise the center of the circle will be aligned with the begin point.
/// The arc's sweep is always less than or equal to 90 degrees.
///
/// See also:
///
30 31
///  * [Tween], for a discussion on how to use interpolation objects.
///  * [MaterialRectArcTween], which extends this concept to interpolating [Rect]s.
32 33
class MaterialPointArcTween extends Tween<Offset> {
  /// Creates a [Tween] for animating [Offset]s along a circular arc.
34
  ///
35 36 37
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
38
  MaterialPointArcTween({
39 40
    Offset? begin,
    Offset? end,
41 42 43 44 45
  }) : super(begin: begin, end: end);

  bool _dirty = true;

  void _initialize() {
46 47 48 49 50
    assert(this.begin != null);
    assert(this.end != null);

    final Offset begin = this.begin!;
    final Offset end = this.end!;
51

52 53 54 55 56
    // An explanation with a diagram can be found at https://goo.gl/vMSdRg
    final Offset delta = end - begin;
    final double deltaX = delta.dx.abs();
    final double deltaY = delta.dy.abs();
    final double distanceFromAtoB = delta.distance;
57
    final Offset c = Offset(end.dx, begin.dy);
58

59
    double sweepAngle() => 2.0 * math.asin(distanceFromAtoB / (2.0 * _radius!));
60 61 62 63

    if (deltaX > _kOnAxisDelta && deltaY > _kOnAxisDelta) {
      if (deltaX < deltaY) {
        _radius = distanceFromAtoB * distanceFromAtoB / (c - begin).distance / 2.0;
64
        _center = Offset(end.dx + _radius! * (begin.dx - end.dx).sign, end.dy);
65 66
        if (begin.dx < end.dx) {
          _beginAngle = sweepAngle() * (begin.dy - end.dy).sign;
67 68
          _endAngle = 0.0;
        } else {
69 70
          _beginAngle = math.pi + sweepAngle() * (end.dy - begin.dy).sign;
          _endAngle = math.pi;
71 72 73
        }
      } else {
        _radius = distanceFromAtoB * distanceFromAtoB / (c - end).distance / 2.0;
74
        _center = Offset(begin.dx, begin.dy + (end.dy - begin.dy).sign * _radius!);
75
        if (begin.dy < end.dy) {
76
          _beginAngle = -math.pi / 2.0;
77
          _endAngle = _beginAngle! + sweepAngle() * (end.dx - begin.dx).sign;
78
        } else {
79
          _beginAngle = math.pi / 2.0;
80
          _endAngle = _beginAngle! + sweepAngle() * (begin.dx - end.dx).sign;
81 82
        }
      }
83 84 85 86 87
      assert(_beginAngle != null);
      assert(_endAngle != null);
    } else {
      _beginAngle = null;
      _endAngle = null;
88
    }
89
    _dirty = false;
90 91
  }

92 93
  /// The center of the circular arc, null if [begin] and [end] are horizontally or
  /// vertically aligned, or if either is null.
94
  Offset? get center {
95 96 97 98 99 100
    if (begin == null || end == null)
      return null;
    if (_dirty)
      _initialize();
    return _center;
  }
101
  Offset? _center;
102

103 104
  /// The radius of the circular arc, null if [begin] and [end] are horizontally or
  /// vertically aligned, or if either is null.
105
  double? get radius {
106 107 108 109 110 111
    if (begin == null || end == null)
      return null;
    if (_dirty)
      _initialize();
    return _radius;
  }
112
  double? _radius;
113

114 115 116 117 118
  /// The beginning of the arc's sweep in radians, measured from the positive x
  /// axis. Positive angles turn clockwise.
  ///
  /// This will be null if [begin] and [end] are horizontally or vertically
  /// aligned, or if either is null.
119
  double? get beginAngle {
120 121 122 123 124 125
    if (begin == null || end == null)
      return null;
    if (_dirty)
      _initialize();
    return _beginAngle;
  }
126
  double? _beginAngle;
127

128
  /// The end of the arc's sweep in radians, measured from the positive x axis.
129
  /// Positive angles turn clockwise.
130 131 132
  ///
  /// This will be null if [begin] and [end] are horizontally or vertically
  /// aligned, or if either is null.
133
  double? get endAngle {
134 135 136 137 138 139
    if (begin == null || end == null)
      return null;
    if (_dirty)
      _initialize();
    return _beginAngle;
  }
140
  double? _endAngle;
141 142

  @override
143
  set begin(Offset? value) {
144 145 146 147
    if (value != begin) {
      super.begin = value;
      _dirty = true;
    }
148 149 150
  }

  @override
151
  set end(Offset? value) {
152 153 154 155
    if (value != end) {
      super.end = value;
      _dirty = true;
    }
156 157 158
  }

  @override
159
  Offset lerp(double t) {
160 161
    if (_dirty)
      _initialize();
162
    if (t == 0.0)
163
      return begin!;
164
    if (t == 1.0)
165
      return end!;
166
    if (_beginAngle == null || _endAngle == null)
167 168 169 170 171
      return Offset.lerp(begin, end, t)!;
    final double angle = lerpDouble(_beginAngle, _endAngle, t)!;
    final double x = math.cos(angle) * _radius!;
    final double y = math.sin(angle) * _radius!;
    return _center! + Offset(x, y);
172 173 174 175
  }

  @override
  String toString() {
176
    return '${objectRuntimeType(this, 'MaterialPointArcTween')}($begin \u2192 $end; center=$center, radius=$radius, beginAngle=$beginAngle, endAngle=$endAngle)';
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  }
}

enum _CornerId {
  topLeft,
  topRight,
  bottomLeft,
  bottomRight
}

class _Diagonal {
  const _Diagonal(this.beginId, this.endId);
  final _CornerId beginId;
  final _CornerId endId;
}

193 194 195 196 197
const List<_Diagonal> _allDiagonals = <_Diagonal>[
  _Diagonal(_CornerId.topLeft, _CornerId.bottomRight),
  _Diagonal(_CornerId.bottomRight, _CornerId.topLeft),
  _Diagonal(_CornerId.topRight, _CornerId.bottomLeft),
  _Diagonal(_CornerId.bottomLeft, _CornerId.topRight),
198 199
];

200
typedef _KeyFunc<T> = double Function(T input);
201 202

// Select the element for which the key function returns the maximum value.
203
T _maxBy<T>(Iterable<T> input, _KeyFunc<T> keyFunc) {
204 205
  late T maxValue;
  double? maxKey;
206
  for (final T value in input) {
207
    final double key = keyFunc(value);
208 209 210 211 212 213 214 215
    if (maxKey == null || key > maxKey) {
      maxValue = value;
      maxKey = key;
    }
  }
  return maxValue;
}

216 217
/// A [Tween] that interpolates a [Rect] by having its opposite corners follow
/// circular arcs.
218
///
219 220 221
/// This class specializes the interpolation of [Tween<Rect>] so that instead of
/// growing or shrinking linearly, opposite corners of the rectangle follow arcs
/// in a manner consistent with material design principles.
222
///
223 224
/// Specifically, the rectangle corners whose diagonals are closest to the overall
/// direction of the animation follow arcs defined with [MaterialPointArcTween].
225
///
226 227
/// See also:
///
228 229
///  * [MaterialRectCenterArcTween], which interpolates a rect along a circular
///    arc between the begin and end [Rect]'s centers.
230
///  * [Tween], for a discussion on how to use interpolation objects.
231
///  * [MaterialPointArcTween], the analog for [Offset] interpolation.
232
///  * [RectTween], which does a linear rectangle interpolation.
233 234
///  * [Hero.createRectTween], which can be used to specify the tween that defines
///    a hero's path.
235
class MaterialRectArcTween extends RectTween {
236 237
  /// Creates a [Tween] for animating [Rect]s along a circular arc.
  ///
238 239 240
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
241
  MaterialRectArcTween({
242 243
    Rect? begin,
    Rect? end,
244 245 246 247 248
  }) : super(begin: begin, end: end);

  bool _dirty = true;

  void _initialize() {
249 250
    assert(begin != null);
    assert(end != null);
251
    final Offset centersVector = end!.center - begin!.center;
252
    final _Diagonal diagonal = _maxBy<_Diagonal>(_allDiagonals, (_Diagonal d) => _diagonalSupport(centersVector, d));
253
    _beginArc = MaterialPointArcTween(
254 255
      begin: _cornerFor(begin!, diagonal.beginId),
      end: _cornerFor(end!, diagonal.beginId),
256
    );
257
    _endArc = MaterialPointArcTween(
258 259
      begin: _cornerFor(begin!, diagonal.endId),
      end: _cornerFor(end!, diagonal.endId),
260
    );
261
    _dirty = false;
262 263
  }

264
  double _diagonalSupport(Offset centersVector, _Diagonal diagonal) {
265
    final Offset delta = _cornerFor(begin!, diagonal.endId) - _cornerFor(begin!, diagonal.beginId);
266 267 268
    final double length = delta.distance;
    return centersVector.dx * delta.dx / length + centersVector.dy * delta.dy / length;
  }
269

270
  Offset _cornerFor(Rect rect, _CornerId id) {
271 272 273 274 275 276 277 278 279 280
    switch (id) {
      case _CornerId.topLeft: return rect.topLeft;
      case _CornerId.topRight: return rect.topRight;
      case _CornerId.bottomLeft: return rect.bottomLeft;
      case _CornerId.bottomRight: return rect.bottomRight;
    }
  }

  /// The path of the corresponding [begin], [end] rectangle corners that lead
  /// the animation.
281
  MaterialPointArcTween? get beginArc {
282 283 284 285 286 287
    if (begin == null)
      return null;
    if (_dirty)
      _initialize();
    return _beginArc;
  }
288
  late MaterialPointArcTween _beginArc;
289 290 291

  /// The path of the corresponding [begin], [end] rectangle corners that trail
  /// the animation.
292
  MaterialPointArcTween? get endArc {
293 294 295 296 297 298
    if (end == null)
      return null;
    if (_dirty)
      _initialize();
    return _endArc;
  }
299
  late MaterialPointArcTween _endArc;
300 301

  @override
302
  set begin(Rect? value) {
303 304 305 306
    if (value != begin) {
      super.begin = value;
      _dirty = true;
    }
307 308 309
  }

  @override
310
  set end(Rect? value) {
311 312 313 314
    if (value != end) {
      super.end = value;
      _dirty = true;
    }
315 316 317 318
  }

  @override
  Rect lerp(double t) {
319 320
    if (_dirty)
      _initialize();
321
    if (t == 0.0)
322
      return begin!;
323
    if (t == 1.0)
324
      return end!;
325
    return Rect.fromPoints(_beginArc.lerp(t), _endArc.lerp(t));
326 327 328 329
  }

  @override
  String toString() {
330
    return '${objectRuntimeType(this, 'MaterialRectArcTween')}($begin \u2192 $end; beginArc=$beginArc, endArc=$endArc)';
331 332
  }
}
333

334 335 336
/// A [Tween] that interpolates a [Rect] by moving it along a circular arc from
/// [begin]'s [Rect.center] to [end]'s [Rect.center] while interpolating the
/// rectangle's width and height.
337 338 339 340 341 342 343 344 345
///
/// The arc that defines that center of the interpolated rectangle as it morphs
/// from [begin] to [end] is a [MaterialPointArcTween].
///
/// See also:
///
///  * [MaterialRectArcTween], A [Tween] that interpolates a [Rect] by having
///    its opposite corners follow circular arcs.
///  * [Tween], for a discussion on how to use interpolation objects.
346
///  * [MaterialPointArcTween], the analog for [Offset] interpolation.
347 348 349 350 351 352 353 354 355 356
///  * [RectTween], which does a linear rectangle interpolation.
///  * [Hero.createRectTween], which can be used to specify the tween that defines
///    a hero's path.
class MaterialRectCenterArcTween extends RectTween {
  /// Creates a [Tween] for animating [Rect]s along a circular arc.
  ///
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
  MaterialRectCenterArcTween({
357 358
    Rect? begin,
    Rect? end,
359 360 361 362 363 364 365
  }) : super(begin: begin, end: end);

  bool _dirty = true;

  void _initialize() {
    assert(begin != null);
    assert(end != null);
366
    _centerArc = MaterialPointArcTween(
367 368
      begin: begin!.center,
      end: end!.center,
369 370 371 372
    );
    _dirty = false;
  }

373 374
  /// If [begin] and [end] are non-null, returns a tween that interpolates along
  /// a circular arc between [begin]'s [Rect.center] and [end]'s [Rect.center].
375
  MaterialPointArcTween? get centerArc {
376 377 378 379 380 381
    if (begin == null || end == null)
      return null;
    if (_dirty)
      _initialize();
    return _centerArc;
  }
382
  late MaterialPointArcTween _centerArc;
383 384

  @override
385
  set begin(Rect? value) {
386 387 388 389 390 391 392
    if (value != begin) {
      super.begin = value;
      _dirty = true;
    }
  }

  @override
393
  set end(Rect? value) {
394 395 396 397 398 399 400 401 402 403 404
    if (value != end) {
      super.end = value;
      _dirty = true;
    }
  }

  @override
  Rect lerp(double t) {
    if (_dirty)
      _initialize();
    if (t == 0.0)
405
      return begin!;
406
    if (t == 1.0)
407
      return end!;
408
    final Offset center = _centerArc.lerp(t);
409 410
    final double width = lerpDouble(begin!.width, end!.width, t)!;
    final double height = lerpDouble(begin!.height, end!.height, t)!;
411
    return Rect.fromLTWH(center.dx - width / 2.0, center.dy - height / 2.0, width, height);
412 413 414 415
  }

  @override
  String toString() {
416
    return '${objectRuntimeType(this, 'MaterialRectCenterArcTween')}($begin \u2192 $end; centerArc=$centerArc)';
417 418
  }
}